我已经搜索了很多包含组/求和数组值的示例 - 不幸的是我无法解决我的问题。 我得到的数组 $data 看起来像这样:
Array
(
[0] => Array
(
[0] => 1
[1] => 2014
[context] => 'aaa'
)
[1] => Array
(
[0] => 12
[1] => 2014
[context] => 'aaa'
)
[2] => Array
(
[0] => 5
[1] => 2014
[context] => 'zzz'
)
)
我想按“上下文”对它的值(但不是全部)进行分组和求和。
所以期望的输出是:
Array
(
[0] => Array
(
[0] => 13
[1] => 2014
[context] => 'aaa'
)
[1] => Array
(
[0] => 5
[1] => 2014
[context] => 'zzz'
)
)
我离这个预期的输出还很远。我试过类似的东西:
$result = array();
foreach ($data as $subArray)
{
foreach ($subArray as $row)
{
$result[$row['context']] = $row['context'];
$result[$row['1']] = $row['1'];
$result[$row['0']] += $row['0'];
}
}
但是当然不行,我没主意了。你能给我一个提示吗?我还能尝试什么?
问题是您在循环中覆盖了元素,并且您指望额外的嵌套级别:
$data = array(
0 => array(
0 => 1,
1 => 2014,
'context' => 'aaa'
),
1 => array(
0 => 12,
1 => 2014,
'context' => 'aaa'
),
2 => array(
0 => 5,
1 => 2014,
'context' => 'zzz'
)
);
$result = array();
// the elements to sum - since everything is mixed together.
// the values in this array should be the index you want to sum
// ex. $sum = array(2,3) would sum $data[2] and $data[3]
$sum = array(0);
foreach ($data as $subArray)
{
$context = $subArray['context'];
if (!isset($result[$context])) {
// initialize the result for this context because it doesnt exist yet
$result[$context] = array();
}
// you had an extra nesting level here
// $row was equiv to 'aaa' or '2014' whereas you thought it was
// array('context' => 'aaa', 0 => 5, 1 => '2014')
foreach ($subArray as $idx => $val)
{
// you were also constantly overrwriting $result'aaa'] (or whatever context) here
if (in_array($idx, $sum)) {
$result[$context][$idx] = isset($result[$context][$idx])
? $result[$context][$idx] + $val
: $val;
} else {
// this will keep overwriting anything that isnt in the $sum array
// but thats ok because those values should be the same with, or the last
// one should win. If you need different logic than that then adjsut as necessary
$result[$context][$idx] = $val;
}
}
}
printf('<pre>%s</pre>', print_r($result, true));
你可以使用临时数组来完成它(这里是
$newArr
)。可以尝试这样的事情
$newArr = array();
foreach($your_arr as $key=>$val){
$index = $val['context'].$val[1];
if(isset($newArr[$index])){
$val_0 = $newArr[$val['context'].$val[1]][0] + $val[0];
$newArr[$val['context'].$val[1]] = array($val_0, $val[1], 'context'=>$val['context']);
}else{
$newArr[$val['context'].$val[1]] = $val;
}
}
$result = array_values($newArr);
print '<pre>';
print_r($result);
print '</pre>';
使用单个循环并在第一个遇到的具有给定
context
值的行的第一个元素上添加引用。如果多次遇到上下文值,请将其第一个元素的值添加到引用中并取消设置整行。
代码:(演示)
foreach ($array as $i => &$row) {
if (!isset($ref[$row['context']])) {
$ref[$row['context']] = &$row[0]; // create reference
} else {
$ref[$row['context']] += $row[0]; // sum new value and reference value
unset($array[$i]); // remove the unneeded row
}
}
var_export($array);