Array_count_values ​​of a multidimensional array?

I searched this question many times. But I could not find a suitable solution anywhere. Just like you do array_count_values() for a one-dimensional array, what do you do for a multidimensional array if you want to get a similar type of solution?

For instance -

 Array ( [0] => Array ( [07/11] => 134 ) [1] => Array ( [07/11] => 134 ) [2] => Array ( [07/11] => 145 ) [3] => Array ( [07/11] => 145 ) [4] => Array ( [07/12] => 134 ) [5] => Array ( [07/12] => 99 ) ) 

The output I want is

 Date: 07/11, ID: 134, Count: 2 Date: 07/11, ID: 145, Count: 2 Date: 07/12, ID: 135, Count: 1 Date: 07/12, ID: 99, Count: 1 

How to do it?

+4
source share
3 answers

Using the $arr variable for your array, you can do this:

 $out = array(); foreach ($arr as $key => $value){ foreach ($value as $key2 => $value2){ $index = $key2.'-'.$value2; if (array_key_exists($index, $out)){ $out[$index]++; } else { $out[$index] = 1; } } } var_dump($out); 

Output:

 Array ( [07/11-134] => 2 [07/11-145] => 2 [07/12-134] => 1 [07/12-99] => 1 ) 

Here's another version that produces it as a multidimensional array:

 $out = array(); foreach ($arr as $key => $value){ foreach ($value as $key2 => $value2){ if (array_key_exists($key2, $out) && array_key_exists($value2, $out[$key2])){ $out[$key2][$value2]++; } else { $out[$key2][$value2] = 1; } } } 

Output:

 Array ( [07/11] => Array ( [134] => 2 [145] => 2 ) [07/12] => Array ( [134] => 1 [99] => 1 ) ) 
+10
source
 <?php $array = array(array('07/11' => '134'), array('07/11' => '134'), array('07/12' => '145')); $count = array(); foreach ($array as $val) { foreach ($val as $key => $subval) { $count[$key]++; } } print_r($count); 
+1
source

In your place, I would change the structure of the data array. In your case:

 Array( [07/11] => Array ( [0] => 134, [1] => 134, [2] => 145, [3] => 145, ... ) ) 
0
source

Source: https://habr.com/ru/post/1491337/


All Articles