Skip to content
Advertisement

What is the best way to group a php array?

For example, I have this array:

$bills = array(
                 array("bill_id"=>"1", "product_id"=>"1", "total"=>"10"),
                 array("bill_id"=>"2", "product_id"=>"2", "total"=>"20"),
                 array("bill_id"=>"3", "product_id"=>"1", "total"=>"30"),
                 array("bill_id"=>"4", "product_id"=>"1", "total"=>"40"),
                 array("bill_id"=>"5", "product_id"=>"2", "total"=>"50")
            );

We need to add the totals of each produdct into a single array, i.e. What is the best clean fast way to generate the following array from the above one:

 $products = array(
                array("product_id"=>"1", "total"=>"80"),
                array("product_id"=>"2", "total"=>"70")
            );

Advertisement

Answer

the fastest way to sum this is index array, something like this

$products = array();

foreach ($bills as $bill) {
    $key = $bill['product_id'];
    if (isset($products[$key])) {
        $products[$key]['total'] += $bill['total'];
    } else {
        $products[$key] = $bill;
    }
}

var_dump($products);

output

array(2) {
  [1]=>
  array(3) {
    ["bill_id"]=>
    string(1) "1"
    ["product_id"]=>
    string(1) "1"
    ["total"]=>
    int(80)
  }
  [2]=>
  array(3) {
    ["bill_id"]=>
    string(1) "2"
    ["product_id"]=>
    string(1) "2"
    ["total"]=>
    int(70)
  }
}

to browse the invoice list

foreach($products as $key=>$bill) {
    var_dump($bill);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement