Oswaldo C.
Oswaldo C.

Reputation: 99

How to get most repeate item on Multidimensional Array

Good day, Im trying to Get the most repeated inside a foreach loop on php. Each array is a cycle of the loop. I need to get the id and name of the most repeated item, in this example is jake.

This is the loop:

    foreach ($json[$key]['data'] as $user){
      var_dump($user);
    }

and the output is:

    array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }
    array(2) {
      ["id"]=>
      string(4) "1021"
      ["name"]=>
      string(3) "Ana"
    }
    array(2) {
      ["id"]=>
      string(4) "2058"
      ["name"]=>
      string(4) "John"
    }
    array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }

I need the output to be:

    $repeated = array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }

Thanks in advance for all your answers.

Upvotes: 1

Views: 64

Answers (2)

user4628565
user4628565

Reputation:

try this step to remove the duplicates from your array,

$repeated  = array_map("unserialize", array_unique(array_map("serialize", $repeated)));

Upvotes: 0

sevavietl
sevavietl

Reputation: 3792

You don't have to use an explicit loop here:

$counts = array_count_values(array_map(function ($user) {
    ksort($user);
    return json_encode($user);   
}, $users));

arsort($counts);

$result = json_decode(key($counts), true);

Basically, we map array elements to JSON representations. This is done with array_map. And it is done because array_count_values can count only strings or integers. Pay attention that before using json_encode we use ksort. This is needed in case user data is the same but have a different order.

Then we sort descending preserving array keys with arsort.

Finally, we get the first key with key and decode it get the original array element with json_decode.

Here is working demo.

Upvotes: 1

Related Questions