kexxcream
kexxcream

Reputation: 5943

Get most frequent array inside a multidimensional array

Problem:

I wish to get the array that is most reoccuring inside a multidimensional array. Google was not helpful this time around.

Sample array:

Array
(
    [1] => Array
        (
            [iata] => HAV
            [lat] => 22.9892
            [lng] => -82.4091
        )

    [2] => Array
        (
            [iata] => PEK
            [lat] => 40.0801
            [lng] => 116.585
        )

    [3] => Array
        (
            [iata] => HAV
            [lat] => 22.9892
            [lng] => -82.4091
        )
)

Desired output:

Array
(
    [iata] => HAV
    [lat] => 22.9892
    [lng] => -82.4091
)

Upvotes: 1

Views: 121

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Here's one way:

$count  = array_count_values(array_column($array, 'iata'));
arsort($count);
$result = array_column($array, null, 'iata')[key($count)];
  • Get an array of the iata values and count those values
  • Sort them descending (preserving keys)
  • Get an array of the arrays indexed by iata value (they will be unique) and get the one with the key of the highest iata count value

Upvotes: 1

Related Questions