简体   繁体   中英

Php count frequency in multidimensional array

I have a $array and I want to count the frequency of numbers from 1 to 10 stored in $i->x->y .

I did

foreach($array as $i){
if($i->x->y == 1){
$a++;
}elseif ($i->x->y == 2){
$b++;
}elseif ($i->x->y == 3){
$c++;
}
...
array_push($count, $a, $b, $c);

I could do this and it worked but I'm sure there's a more elegant way to do this. There's the array_count_values function but I'm not sure how this is applicable to this situation.

I would start a second array that keeps keys as the number you are tracking with a value holding the count of that number. Example:

$array = array(1,2,3,5,4,7,5,6,9,8,10,4,6,8,7,1,3,6,8,7,10,5,8,3);
$counts = array();
foreach($array as $i) {
    if(array_key_exists($i, $counts)) {
        $counts[$i]++;
    } else {
        $counts[$i] = 1;
    }
}

Doing a var_dump($counts); produces this:

array(10) {
  [1]=>
  int(2)
  [2]=>
  int(1)
  [3]=>
  int(3)
  [5]=>
  int(3)
  [4]=>
  int(2)
  [7]=>
  int(3)
  [6]=>
  int(3)
  [9]=>
  int(1)
  [8]=>
  int(4)
  [10]=>
  int(2)
}

Hope that helps you out some.

I made a test using a frequency array that has counter to each number from 1 to zero

// random numbers to validate
$rnd_arr = array();
// freq array
$freq;

// random numbers
for($i = 0; $i < 500; $i++) {
    array_push($rnd_arr, rand(1, 10));
}

// initiate the counter for each number from 1 to 10
for ($i=1; $i < 10; $i++) { 
    # code...
    $freq[(string) $i] = 0;
}

// check the frequency
for($i = 0; $i < 500; $i++) {
    $freq[(string) $rnd_arr[$i]]+= 1;
}

print_r($freq);

// random output
Array ( [1] => 53 [2] => 61 [3] => 48 [4] => 68 [5] => 48 [6] => 40 [7] => 45 [8] => 56 [9] => 36 [10] => 45 )

if its not exactly what you need just post your code then i can help. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM