I am using nested arrays to create a 2D matrix. Its pretty easy too find the sum of all the values in the rows using nested foreach loops. However, I cant figure out how to do a sum down each column. ie: I want to find the sum of the score for each item.
Any suggestions? Thank you!!! 🙂
PS: Note that some of the cells in the array have no values. These will be taken as 0.
Sum across row
foreach($critics as $array) {
foreach($array as $item => $score) {
$row_sum += $score;
}
}
The Nested Array
$critics['Lisa Rose'] = array(
'Lady in the water' => 2.5,
'Snakes on a plane' => 3.5,
'Just my luck' => 3.0,
'Superman returns' => 3.5,
'You, me and dupree' => 2.5,
'The night listener' => 3.0
);
$critics['Gene Seymour'] = array(
'Lady in the water' => 3.0,
'Snakes on a plane' => 3.5,
'Just my luck' => 1.5,
'Superman returns' => 5.0,
'You, me and dupree' => 3.5,
'The night listener' => 3.0
);
$critics['Michael Phillips'] = array(
'Lady in the water' => 2.5,
'Snakes on a plane' => 3.0,
'Superman returns' => 3.5,
'The night listener' => 4
);
$critics['Claudia Puig'] = array(
'Snakes on a plane' => 3.5,
'Just my luck' => 3.0,
'Superman returns' => 4.5,
'You, me and dupree' => 4.0,
'The night listener' => 2.5
);
$critics['Mick LaSalle'] = array(
'Lady in the water' => 3.0,
'Snakes on a plane' => 4.0,
'Just my luck' => 2.0,
'Superman returns' => 3.0,
'You, me and dupree' => 3.0,
'The night listener' => 2.0
);
$critics['Jack Matthews'] = array(
'Lady in the water' => 3.0,
'Snakes on a plane' => 4.0,
'Just my luck' => 2.0,
'Superman returns' => 3.0,
'You, me and dupree' => 3.5,
);
$critics['Toby'] = array(
'Snakes on a plane' => 4.5,
'Just my luck' => 1.0,
'Superman returns' => 4.0
);
Which has output like this: