I've searched a lot of examples with group/sum array values - unfortunately I can't resolve my problem. I got array $data which looks like this:
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'
)
)
I would like to group and sum its values (but not all) by 'context'.
So desired output is:
Array
(
[0] => Array
(
[0] => 13
[1] => 2014
[context] => 'aaa'
)
[1] => Array
(
[0] => 5
[1] => 2014
[context] => 'zzz'
)
)
I'm far from this expected output. I've tried something like:
$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'];
}
}
But of course it doesn't work and I'm out of ideas. Can you please give me a hint? What else can I try?
The problem is you were overwriting elements in your loop and you were counting on an extra nesting level:
$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));
0 comments:
Post a Comment