Jump to content

multidimensional array, summing same keys; wrong count value


AndyPSV

Recommended Posts

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

 

I've get after launching.

 

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']++;
}

 

I get.

 

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

 

where I should get.

 

array ( 6 => array ( 'id' => '6', 't' => 'Food & Beverage', 'cnt' => [b]4[/b], ), 2 => array ( 'id' => '2', 't' => 'Automotive', 'cnt' => 2, ), )

 

How can I fix this issue?

 

-----------------------------------------------------

 

I've received solution on other board.

 

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

$return = array();
$count = array();
foreach( $array as $item ) {
    if ( !in_array($item, $return) ) {
        $return[] = $item;
        $count[ $item['id'] ] = 1;
    } else {
        $count[ $item['id'] ]++;
    }
}

foreach( $return as & $item ) {
    $item['cnt'] = (int)$count[ $item['id'] ];
}

var_dump( $return );

 

 

thank you

 

---

 

the code above works too, I've put it in WHILE() and didn't noticed it. Sorry

 

Thanks

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.