0

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!

1 Answer 1

2

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.

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

3 Comments

You don't address the issue that array('678073776', '704322062') could be equal to array('704322062', '678073776'). The question doesn't say anything about this.
@KIKOSoftware good point – should that also be a requirement, then $item could be sorted first, before it gets encoded as JSON and added to the temp array.
Thanks so much - this has worked perfectly @CBroe And I just dropped in a sort on $item to @KIKOSoftware's point. Thank you both!

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.