I have a mulit demensional array like this ...
** note the array has closing brackets which is not shown in this image. so theres no issue in the syntax.
I want to add the values in each key (Openness, Conscientiousness) together so that i have a array like :
Array{
[Openness]=> Array(
[0] => 16
)
[Conscientiousness]=>Array (
[0]=> 10
)
}
When i tried this code after looking through existing questions :
$sumArray = array();
foreach ($finalarr as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
//$sumArray[$id]+=$value;
array_key_exists( $id, $sumArray ) ? $sumArray[$id] += $value : $sumArray[$id] = $value;
}
}
print_r($sumArray);
I get :
which is not what i want. ANy ideas how to fix the array?
You can do it with array_sum()
and one loop:
$sumArray = array();
foreach ($finalarr as $k => $subArray) {
$sumArray[$k] = array_sum($subArray);
}
If you really need the elements of $sumArray
to be arrays rather than just the sums, it becomes:
$sumArray = array();
foreach ($finalarr as $k => $subArray) {
$sumArray[$k] = array(array_sum($subArray));
}
But I'm not sure why you would want that.
Okay as suggested in the comments i used the array_sum and it worked. I changed the foreach to :
**removed the inner loop which was unnecessary
foreach ($finalarr as $k=>$subArray) {
$finalarr[$k]=array_sum($subArray);
}
and it gave me the output :
Array{
[Openness]=> 16
[Conscientiousness]=> 10
}
Thanks for the comments !!