Mac Taylor
Mac Taylor

Reputation: 5166

most common values in a multidemensional array

My question is maybe repetitive but I really find it hard. (I have read related topics)

This is the array :

Array
(
    [0] => Array
        (
            [legend] => 38440
        )

    [1] => Array
        (
            [bestw] => 9765
        )

    [2] => Array
        (
            [fiuna] => 38779
        )

    [3] => Array
        (
            [adam] => 39011
        )

    [4] => Array
        (
            [adam] => 39011
        )

    [5] => Array
        (
            [adam] => 39011
        )

)

I have tried many ways to handle this array and find out the most common value. The result I expect is "adam"

$countwin = array_count_values($winnernames);
$maxwin = max($countwin);
$mostwinner = array_keys($countswin, $maxwin);

EDIT : My array is like this array("A"=>"1" , "B"=>"2" , "A"=>"1") it should return A is the most common

Upvotes: 0

Views: 122

Answers (2)

rodneyrehm
rodneyrehm

Reputation: 13557

How about iterating your array and counting the values you've got?

$occurences = array();
foreach ($data as $row) {
  foreach ($row as $key => $score) {
    if (empty($occurences[$key])) {
      $occurences[$key] = 1;
    } else {
      $occurences[$key]++;
    }
  }
}

and then sorting that

arsort($occurences);

and grabbing the first element of the sorted array

$t = array_keys($occurences);
$winner = array_shift($occurences);

Upvotes: 2

Munim
Munim

Reputation: 2778

You may try this code. A brute force method indeed. But a quick search made me to find this an useful one:

function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}

EDIT : Sorry, I misinterpreted your question! But it might be the first hint of finding the one with maximum counter.

Upvotes: -1

Related Questions