Sum amount of repeated PHP variables

Asked

Viewed 777 times

1

The code snippet below returns me names and quantities of products, each in a variable.

foreach ($orderItems as $order) {
    $order_data = Mage::getModel('sales/order')->load($order['order_id']);
    $items = $order_data->getAllItems();
    $order_id = $order['order_id'];
    $total = $order_data->getGrandTotal();
    $customer_name = $order_data->getCustomerName();

    foreach ($items as $item) {
        $product_id = $item->getProductId();
        if ($product_id == $id) {
             $tudo = $item->getName() .' - Quantidade: '. $item->getQtyOrdered().'<br/>';
        }
    }
        
    echo $tudo;
    }

Output example:

Product 1 - Quantity: 2

Product 1 - Quantity: 7

Product2 - Quantity: 1

Product2 - Quantity: 1

How could I make the way out next?

Product 1 - Quantity: 9

Product 2 - Quantity: 2

  • I have identified your code for easy reading. The echo $tudo is inside the foreach $oderItems? Is that it lacks the closure }, it must have been at the time of making copy/Paste here...

  • yes, the echo $everything is inside the foreach $oderItems.

3 answers

1

Instead of putting the result in $everything, the easy option would be to use in a "$everything" table. Here a solution, very basic.

    // Init quantidade
    foreach ($items as $item)
    {
           $product_id = $item->getProductId();
          $tudo[$product_id] = 0;     // Para cada Product, qt do inicio = 0
    }

    // Leitura das quantidades
     foreach ($items as $item) {
          $product_id = $item->getProductId();
           // Acumulação...
          $tudo[$product_id] = $tudo[$product_id] + $item->getQtyOrdered();
    }

Here, you need to see how many "everything" you have using $num_tudo = sizeof($everything);

and loop to read the result.

In the first version, the third foreach was wrong.

Other option:

<?php

// Os dados que vamos contar
 $data = "truc,truc,machin,truc,machin,bidule,bidule,truc,truc";


$tab_data = explode(",",$data);
$nb_data = sizeof($tab_data);
 // 1- Preparar
for ($x=0; $x<$nb_data; $x++)
{
     $nome_prod = $tab_data[$x];
    $qt_data[$nome_prod] = 0;
}

 // Contar
 for ($x=0; $x<$nb_data; $x++)
 {
    $nome_prod = $tab_data[$x];
    $qt_data[$nome_prod]++;
 }


 // Aqui, temos mais de uma vez cada resultado

  // Vai dar para nos SOMENTE as keys de verdade
  $dest =  array_keys($qt_data);

 foreach ($dest as $key=>$value)
 {
     echo $value."=".$qt_data[$value]."<br>\n";
 }

 ?>
  • In the first foreach had to check whether $tudo[id] already exists, no?

  • Hello Peter, thanks for the help! I did as you said (or at least as I understood) and the result was the sum of all Qt. resulted in 11

0

Dude I had a similar problem and I solved it like this:

for ($i = 0; $i < count($array); $i++) {

    if (isset($array[$i])) {
        $nome = $array[$i]["nome"]//o nome do produto
            //assim ele passa por todos os elementos
            for ($j = $i + 1; $j < count($array); $j++) {

                    if (isset($array[$j])) {
                        $nome2 = $array[$j]["nome"];                            

                        if ($nome == $nome2){
                            $valor  = (int)$array[$i]["v"];//valor do produto
                            $valor2 = (int)$array[$j]["v"];//valor do segundo produto    

                            //se os nomes forem iguais soma os valores
                            $array[$i]["c"][1]["v"] = $valor + $valor2;    

                            //e exclui um dos produtos do array
                            unset($array[$j]);
                        }
                    }
                }
            }
        }

Now you just have to adapt

0

Try adding a group by in the order products, would look something like this:

$items = $order_data->getCollection()->getSelect()->group('product_id');

or

$items = $order_data->getAllItems()->getSelect()->group('product_id');
  • where this group by should be inserted?

  • Replace ($items = $order_data->getAllItems();) with one of these and test to see if it’s right.

Browser other questions tagged

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