kh_9
kh_9

Reputation: 1

How do you find most common array in multidimensional array using PHP

I need to find the most common (most occurring) array in a multidimensional array. Not the most common values like this post - Find Common most values in multidimensional array in PHP - but rather the most common combination.

For example, if I have the following:

$a1=array(
    array('704322062'),
    array('678073776', '704322062'),
    array('678073776', '704322062'),
    array('704322064'),
    array('704322062'),
    array('678073776'),
    array('678073776', '704322062')
);

I want to be able to detect that the array that occurs most often is array('678073776', '704322062') not that the string '704322062' is most common.

I've tried using array_intersect but couldn't get it working for this scenario.

Thanks!

Upvotes: 0

Views: 57

Answers (1)

C3roe
C3roe

Reputation: 96383

array_count_values only works with scalar values, not when the items are arrays themselves. But we can still use that function, if we transform your arrays into strings first - by encoding them as JSON.

// fill temp array with items encoded as JSON
$temp = [];
foreach($a1 as $item) {
  $temp[] = json_encode($item);
}

// count how many times each of those values occurs
$value_counts = array_count_values($temp);
// sort by number of occurrence, while preserving the keys
ksort($value_counts);

// pick the first key from the temp array
$first = array_key_first($value_counts);

This will get you ["678073776","704322062"] in $first now - you can json_decode it again, if you want your “original” array.

Note that this does not take into account, that two arrays could occur the same amount of times - then it will just pick the “random” first one of those. If you need to handle that case as well somehow, then you can determine the maximum value in $temp first, and then filter it by that value, so that only those keys of the corresponding arrays will be left.

Upvotes: 2

Related Questions