Jump to content

multidimensional array, summing same keys


AndyPSV

Recommended Posts

array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 1 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 2 => array ( 'id' => '2', 't' => 'Automotive', ), )

 

how to sum it, to get:

 

array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', 'cnt' => '2' ), 1 => array ( 'id' => '2', 't' => 'Automotive', 'cnt' => '1' ), )

Maybe overly complex but I have a cold and my brain is fuzzy:

 

$new_array  = array();

foreach($array as $value) {
    if(isset($new_array[$value['id']])) {
        $new_array[$value['id']]['cnt']++;
    } else {
        $new_array[$value['id']] = $value;
        $new_array[$value['id']]['cnt'] = 1;
    }
}

No simpler, but shorter  :-\

 

foreach($array as $value) {
    if(!isset($new_array[$value['id']])) {
        $new_array[$value['id']] = $value;
        $new_array[$value['id']]['cnt'] = 0;
    }
    $new_array[$value['id']]['cnt']++;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.