我有这样的数组。 我正在尝试找到具有相同数组键的所有元素的总和。
预期输出:Array ( [JOHN] => 25000 [SMITH] => 13000 [ALEX] => 40000 [JAMES] => 16000 [ANTONY] => 28000 )
但我得到的是不同的东西。
$amounts = array( 'JANUARY' => array('JOHN' => array(2000, 5000, 3000), 'SMITH' => array(2000, 1000, 1000, 6000)), 'FEBRUARY' => array('ALEX' => array(5000, 7000, 4000), 'JAMES' => array(4000, 1000, 3000, 2000)), 'MARCH' => array('ANTONY' => array(7000, 2000, 4000), 'JOHN' => array(3000, 5000, 6000, 1000)), 'APRIL' => array('ANTONY' => array(2000, 4000, 6000, 3000), 'ALEX' => array(7000, 8000, 9000)), 'MAY' => array('SMITH' => array(1000, 2000), 'JAMES' => array(2000, 3000, 1000)) );
foreach($amounts as $key => $value)
{
$sum=array();
foreach($value as $key1 => $value1)
{
$sum[$key1] = array_sum($value1);
}
print_r($sum);
}
我得到的输出是:
Array
(
[JOHN] => 10000
[SMITH] => 10000
)
Array
(
[ALEX] => 16000
[JAMES] => 10000
)
Array
(
[ANTONY] => 13000
[JOHN] => 15000
)
Array
(
[ANTONY] => 15000
[ALEX] => 24000
)
Array
(
[SMITH] => 3000
[JAMES] => 6000
)
预期输出:Array ( [JOHN] => 25000 [SMITH] => 13000 [ALEX] => 40000 [JAMES] => 16000 [ANTONY] => 28000 )
答案 0 :(得分:1)
这是你想要的吗?
$amounts = array( 'JANUARY' => array('JOHN' => array(2000, 5000, 3000), 'SMITH' => array(2000, 1000, 1000, 6000)), 'FEBRUARY' => array('ALEX' => array(5000, 7000, 4000), 'JAMES' => array(4000, 1000, 3000, 2000)), 'MARCH' => array('ANTONY' => array(7000, 2000, 4000), 'JOHN' => array(3000, 5000, 6000, 1000)), 'APRIL' => array('ANTONY' => array(2000, 4000, 6000, 3000), 'ALEX' => array(7000, 8000, 9000)), 'MAY' => array('SMITH' => array(1000, 2000), 'JAMES' => array(2000, 3000, 1000)) );
$sum=array();
foreach($amounts as $key => $value)
{
foreach($value as $key1 => $value1)
{
//check key set or not. if not set then assign value 0. so that you dont get undefine index error
if(!isset($sum[$key1]))
$sum[$key1] = 0;
$sum[$key1] += array_sum($value1);
}
}
print_r($sum);
答案 1 :(得分:1)
您的尝试很接近,只需要进行此修改:
//initialise this before foreach, so that it doesn't gets reset in between.
$sum=array();
foreach($amounts as $key => $value) {
foreach($value as $key1 => $value1) {
//Add the previous sum too, so that it doesn't calculate the new sum
if(!array_key_exists($key1, $sum)) {
$sum[$key1] = 0;
}
$sum[$key1] += array_sum($value1);
}
}
//Debug this at the last and not inside the loop.
print_r($sum);