Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count same values in multidimensional array

Tags:

arrays

php

I need to count the same values in multidimensional array and remove duplicates

My array now

[0] => Array
    (
        [id] => 1
        [title] => BMW
    )

[1] => Array
    (
        [id] => 1
        [title] => BMW
    )

[2] => Array
    (
        [id] => 2
        [title] => Mercedes
    )       
.......

Need to output

[0] => Array
    (
        [id] => 1
        [title] => BMW
        [count] => 2
    )

[1] => Array
    (
        [id] => 2
        [title] => Mercedes
        [count] => 1
    )       

I will be very grateful for your help

like image 580
Dizzy Avatar asked Dec 24 '22 23:12

Dizzy


1 Answers

The key problem is that an array(that with an id and a title) is not hashable.

So we can try to hash it, just join them all together, and make the result string as a hash key.

So, we maintain a hash table, which key is the object hash key, and the value is the result array index.

And then, For each item we travel, we can find the result array position by the help of the hash table, and then add the count.

Here's my code.

<?php

$array_in = array(
    array('id'=>1, 'title'=>'BMW'),
    array('id'=>1, 'title'=>'BMW'),
    array('id'=>2, 'title'=>'Mercedes'),
);

$hash = array();
$array_out = array();

foreach($array_in as $item) {
    $hash_key = $item['id'].'|'.$item['title'];
    if(!array_key_exists($hash_key, $hash)) {
        $hash[$hash_key] = sizeof($array_out);
        array_push($array_out, array(
            'id' => $item['id'],
            'title' => $item['title'],
            'count' => 0,
        ));
    }
    $array_out[$hash[$hash_key]]['count'] += 1;
}

var_dump($array_out);
like image 90
Alfred Huang Avatar answered Jan 06 '23 13:01

Alfred Huang