我有这个数组(更长的时间 - 只有部分)
[366] => Array
(
[0] => 8
[1] => 7
[2] => 8
[3] => 9
[4] => 8
)
[367] => Array
(
[0] => 8
[1] => 9
[2] => 9
[3] => 10
[4] => 10
[5] => 9
[6] => 8
[7] => 9
[8] => 10
[9] => 10
[10] => 11
[11] => 10
[12] => 11
[13] => 11
[14] => 10
[15] => 9
[16] => 10
[17] => 8
[18] => 10
)
必须保留密钥(有一个id)。我想总结一下foreach的值(在这个例子中,值是代数)。所以第8代计算为366次计数3次。
期望是id 366:7 - 1x,8 - 3x,9 - 1x或
[366] => Array
(
[7] => 1
[8] => 3
[9] => 1
)
[367] => Array
(
[8] => 3
[9] => 5
[10] => 8
[11] => 3
)
每个建议都受到欢迎和赞赏!
我总是用数字键或foreach停止...我试过的代码之一:
$outdams = array();
foreach ($dams as $key => $value) {
foreach ($value as $key2 => $value2) {
$index = $value2;
if (array_key_exists($index, $outdams)) {
$outdams[$index]++;
} else {
$outdams[$index] = 1;
}
}
}
答案 0 :(得分:3)
检查此代码
<?php
$data = array(366=>array(8,7,8,8,9),
367=>array(8,9,13,14,17,14));
echo "<pre>"; print_r($data);
$response = array();
foreach ($data as $outerkey => $outerData){
foreach ($outerData as $innerkey => $innerData){
//echo "<pre>"; print_r($innerData);
if(array_key_exists($innerData, $response[$outerkey])){
$response[$outerkey][$innerData] ++;
}else{
$response[$outerkey][$innerData] = 1;
}
}
}
echo "<pre>"; print_r($response);
?>