Mahesh
Mahesh

Reputation: 1593

PHP multidimensional array - Counting the duplicate and mingle the duplicate with original

$users = array(
              array(1,'name1'),
              array(1,'name1'),
              array(2,'name2'),
              array(3,'name3')
         );

Now after adding the following code, i can make the unique array.

array_map("unserialize", array_unique(array_map("serialize", $users)));

I can count the duplicates with the following code. But it is missing the name field. So, i need to do something to get the name along with the id and count of duplicate.

array_count_values(array_map(function($item) {
        return $item['id'];
    }, $users));

Do i need to loop the array get something like this? Or is there any other trick in php?

$new_users = array(
              array(1,'name1', 2), //two times + descending order 
              array(2,'name2', 1), 
              array(3,'name3', 1)
         );

Upvotes: 2

Views: 71

Answers (1)

deceze
deceze

Reputation: 522042

$new_users = array_reduce($users, function (array $new_users, array $user) {
    $key = sha1(serialize($user));
    if (isset($new_users[$key])) {
        $new_users[$key][2]++;
    } else {
        $new_users[$key] = array_merge($user, [1]);
    }
    return $new_users;
}, []);

To deduplicate, use unique keys in an array. Here we use the hash of the serialised array as key, which is the simplest way to uniquely identify something more complex than a single value. Then simply increase a counter if the item already exists.

Upvotes: 2

Related Questions