2
$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)
         );
4
  • Upvote for using the word "mingle". It feels like an 80' school dance. Commented Oct 13, 2015 at 9:03
  • Not exactly same, but a similar question here - stackoverflow.com/questions/14202108/… Commented Oct 13, 2015 at 9:09
  • 1
    Instead of showing a bunch of almost correct code, describe what you're actually trying to achieve. You want to merge all duplicates into one item and count the number of duplicates? Commented Oct 13, 2015 at 9:11
  • @deceze I am updating the final result which i am expecting. It is all working good. Is there anyway to achieve them in shortest code to reduce the work load. Commented Oct 13, 2015 at 9:15

1 Answer 1

2
$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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.