Higher value in an array in PHP

Asked

Viewed 812 times

4

I’m having a problem finding the highest value of the box width of the products for shipping a site I’m doing.

I put the data of the products with the size of the boxes in the database and I am now doing the calculations. I needed to add the weight and heights as the customer requested and now I need to take the largest length and width of a set of products, but I’m not able to do it...

If anyone can help would be great, follow the code below:

$total = 0;
            $alturaTotal = 0;
            $pesoTotal = 0;
            $larguraTotal = 0;
            foreach($_SESSION['carrinho'] as $id => $quantidade)
            {
                $sql = "SELECT * FROM produtos WHERE id = '$id'";
                $query = mysql_query($sql);

                while($row = mysql_fetch_assoc($query)) 
                {
                    $produto = $row['nome'];
                    $preco = $row['preco'];
                    $id = $row['id'];
                    $altura = $row['altura'];
                    $largura = $row['largura'];
                    $comprimento = $row['comprimento'];
                    $peso = $row['peso'];
                    $cepOrigem = $row['cepOrigem'];

                    $sub = $preco * $quantidade;
                    $total = $total + $sub;

                    $alturaTotal = $alturaTotal + $altura;
                    $pesoTotal = $pesoTotal + $peso;

                    foreach($_SESSION['carrinho'] as $id => $largura)
                    {
                        $larguraTotal = $largura;   
                    }

1 answer

5


The logic is quite simple, just use two variables and check if the value of the width/length is greater than what is in the variable, if it stores the new value width/length in it. Example:

// Declara as variáveis fora do loop
$maiorlargura = 0;
$maiorcomprim = 0;

// Atualiza o valor da variável dentro do loop
if ($maiorlargura < $largura = $row['largura'])
   $maiorlargura = $largura = $row['largura'];

if ($maiorcomprim < $comprimento = $row['comprimento'])
   $maiorcomprim = $row['comprimento'];

When the loop finish, will be the highest value in the variable. You can still take the product ID, updating a variable to it along with width/length.

  • 1

    Dude Big Brother really helped the/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.