-1

I have this array:

Array ( 
    [0] => stdClass Object ( [id] => 123 [name] => Alex ) 
    [1] => stdClass Object ( [id] => 124 [name] => John ) 
    [2] => stdClass Object ( [id] => 123 [name] => Alex ) 
    [3] => stdClass Object ( [id] => 124 [name] => John) 
    [4] => stdClass Object ( [id] => 126 [name] => Paul )
 )

And I want to output like the following:

 Array ( 
    [0] => Array ( [id] => 123 [name] => Alex [count] = 2 ) 
    [1] => Array ( [id] => 124 [name] => John [count] = 2 ) 
    [2] => Array ( [id] => 126 [name] => Paul [count] = 1 )
  )

I tried using array_count_values($array), but it doesn't work.

Any ideas how to solve this?

0

1 Answer 1

1

You can simply use array_map along with simple foreach like as

foreach(array_map("get_object_vars",$arr) as $val){
    $hash = $val['id'];
    if(isset($result[$hash])){
        $result[$hash]['count'] += $result[$hash]['count'];
    }else{
        $result[$hash] = $val;
        $result[$hash]['count'] = 1;
    }
}
print_r(array_values($result));

Output:

Array
(
    [0] => Array
        (
            [id] => 123
            [name] => Alex
            [count] => 2
        )

    [1] => Array
        (
            [id] => 124
            [name] => John
            [count] => 2
        )

    [2] => Array
        (
            [id] => 126
            [name] => Paul
            [count] => 1
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.