我经常搜索这个问题。但我无法在任何地方找到合适的解决方案。就像你为一维数组做一个array_count_values()
一样,如果你想要一个类似的解决方案,你会对多维数组做什么?
例如 -
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
)
)
我想要的输出是 -
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
我该怎么做?
答案 0 :(得分:12)
对数组使用变量$arr
,您可以这样做:
$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);
输出:
Array
(
[07/11-134] => 2
[07/11-145] => 2
[07/12-134] => 1
[07/12-99] => 1
)
这是另一个将其生成为多维数组的版本:
$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;
}
}
}
输出:
Array
(
[07/11] => Array
(
[134] => 2
[145] => 2
)
[07/12] => Array
(
[134] => 1
[99] => 1
)
)
答案 1 :(得分:2)
<?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);
答案 2 :(得分:0)
在你的位置我会改变数据数组的结构。在你的情况下:
Array(
[07/11] => Array
(
[0] => 134,
[1] => 134,
[2] => 145,
[3] => 145,
...
)
)
答案 3 :(得分:0)
聪明的方法,我们知道array_count_values()
:计算数组的所有值
就像您对一维数组执行 array_count_values() 一样,您对多维数组执行什么操作。
我们把它变成一维数组,然后我们调用函数
$input = array(
array('07/11' => '134'),
array('07/11' => '134'),
array('07/11' => '145'),
array('07/11' => '145'),
array('07/12' => '134'),
array('07/12' => '99')
);
$output = [];
foreach ($input as $inner){
foreach ($inner as $key => $value){
$output[] = "Date: $key, ID: $value, Count:";
}
}
输出:如您所料
foreach(array_count_values($output) as $key => $value) {
echo "$key $value<br>";
}
/*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*/