I have data below :
Array(
[A] => Array
(
[AA] => 10
)
[B] => Array
(
[BA] => 5
[BB] => 1
[BC] => -2
)
[C] => Array
(
[CA] => 3
[CB] => 0
)
)
I want to sum the value of second element my array (BA,BB,BC, etc) like this :
Array(
[A] => 10
[B] => 4
[C] => 3
)
I've tried to do with foreach (I'm using php as my platform) but the result is wrong, can someone give me explanation and the logic to solve this? thanks
You can loop thru your array and use array_sum
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$result = array();
foreach( $arr as $key => $val ){
$result[$key] = array_sum ( $val );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[A] => 10
[B] => 4
[C] => 3
)
This should work for arrays like the one of your example:
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$res = array();
foreach($arr as $key => $value) {
foreach($value as $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
echo "<pre>";
print_r( $res );
echo "</pre>";
This is working without using an inbuilt function.
if you want sum column
<?php
$array = array
(
"A"=>array
(
"AA" => 10,
),
"B"=>array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C"=>array
(
"CA" => 3,
"CB" => 0
)
);
foreach ($array as $key=>$value)
{
$mehrdad[]=$key;
}
foreach ($mehrdad as $key1=>$value1)
{
$arrays=$array[$value1];
foreach ($arrays as $key2=>$value2)
{
$mehrdadi[]=$key2;
}
}
$mehrdadend=array_unique($mehrdadi);
$mehrdadis = array();
foreach ($mehrdadend as $key3=>$value3)
{
$sum=array_sum(array_column($array, $value3));
$mehrdadis[$value3] = $sum;
}
print_r($mehrdadis);
?>
Result
Array
(
[AA] => 10
[BA] => 5
[BB] => 1
[BC] => -2
[CA] => 3
[CB] => 0
)