array_count_values of a multi dimensional array?
✔ Recommended Answer
Using the variable $arr
for your array, you could 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 ))
Source: stackoverflow.com
Answered By: Expedito
The array_count_values()
function in PHP counts the frequency of each value in a one-dimensional array. If you want to count the frequency of values in a multi-dimensional array, you can use a loop to iterate over each element in the array and then use the array_column()
and array_count_values()
functions to count the frequency of each value.
Here's an example code snippet that demonstrates this approach:
php// Example multi-dimensional array
$array = array(
array('a', 'b', 'c'),
array('b', 'c', 'd'),
array('c', 'd', 'e')
);
// Flatten the array using array_column() and count the frequency of each value using array_count_values()
$flat_array = array_column($array, null);
$counts = array_count_values($flat_array);
// Print the frequency of each value
foreach ($counts as $value => $count) {
echo "$value occurs $count times\n";
}
In this example, we first use array_column()
to flatten the multi-dimensional array into a one-dimensional array. We then use array_count_values()
to count the frequency of each value in the flattened array. Finally, we loop over the resulting counts array to print out the frequency of each value.
Comments
Post a Comment