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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.