I am doing the exercise in Learning PHP5 from Oreilly and the task is to caculate to total population of states (with a limited number of cities).
I have created a multidimensional array with states and then inside cities but unlike what is proposed as solution in the book, I am trying to use the sum_array() function to calculate, for each state, the population.
My logic must be somehow wrong as I array_sum doesn't seem to know which array to use (I triple-checked the names and I wrote the good array name). What am I missing?
Here's what I have so far:
$population = array (
'NY' => array('New York' => 8008278),
'CA' => array('Los Angeles' => 3694820, 'San Diego' => 1223400),
'IL' => array('Chicago' => 2896016),
'TX' => array('Houston' => 1953631, 'Dallas' => 1188580, 'San Antonio' => 1144646),
'PA' => array('Philadelphia' => 1517550),
'AZ' => array('Phoenix' => 1321045),
'MI' => array('Detroit' => 951270)
);
print '<table><tr><th>State</th><th>City</th><th>Population</th></tr>';
foreach ($population as $state => $city_info) {
foreach ($city_info as $city_name => $city_population) {
print "<tr><td>$state</td><td>$city_name</td><td>$city_population</td></tr>";
}
print "<tr><td></td><td>{$state}'s total population</td><td>array_sum($city_info)</td></tr>";
}
print "<tr><td></td><td></td></tr>";