I have searched this question a lot. But I could not find a proper solution anywhere. Just like you do an array_count_values()
for a single dimensional array, what do you do for a multi dimensional array if you want similar type of a solution?
For example-
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 that 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 do I do this?
The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
Multidimensional arrays are an extension of 2-D matrices and use additional subscripts for indexing. A 3-D array, for example, uses three subscripts. The first two are just like a matrix, but the third dimension represents pages or sheets of elements.
The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array.
Advantages: ➢ It is used to represent multiple data items of same type by using only single name. ➢ It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc. ➢ Multidimensional arrays are used to represent matrices.
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
)
)
<?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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With