1

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
)
4
  • By iata key or any key? Commented May 20, 2016 at 17:48
  • @FelippeDuarte By iata key. That should have been in my description, sorry about that. Commented May 20, 2016 at 17:48
  • Even if other values are different? Or you want to compare all values and see which array is the most frequent? Commented May 20, 2016 at 17:51
  • Yes, even if other values are different. IATA codes are always unique so I won't have a problem down the road with comparing this value. Commented May 20, 2016 at 17:52

1 Answer 1

1

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