如何按升序组织表格的“州人口”?

时间:2019-01-29 03:28:03

标签: php arrays

我希望能够基于“州人口”中的金额来组织所有其他行。不幸的是,我只知道如何使用通用的ksort来按“城市人口”的值来组织表格:

ksort($ cities);

我该如何特别跟踪“州人口”中的值然后对其进行排序?

<?php 


/*1. According to the US Census Bureau, the 10 largest American cities (by popula‐
tion) in 2010 were as follows:

New York, NY (8,175,133 people)
Los Angeles, CA (3,792,621)
Chicago, IL (2,695,598)
Houston, TX (2,100,263)
Philadelphia, PA (1,526,006)
Phoenix, AZ (1,445,632)
San Antonio, TX (1,327,407)
San Diego, CA (1,307,402)
Dallas, TX (1,197,816)
San Jose, CA (945,942)
Define an array (or arrays) that holds this information about locations and popu‐
lations. Print a table of locations and population information that includes the
total population in all 10 cities.
2.
Modify your solution to the previous exercise so that the rows in the result table
are ordered by population. Then modify your solution so that the rows are
ordered by city name.
3.
Modify your solution to the first exercise so that the table also contains rows that
hold state population totals for each state represented in the list of cities.
*/




$cities = array( array("City"=>"New York", "State"=> "NY", "City Population"=>8175133, "State Population" => 2000),
               array("City"=>"Los Angeles", "State"=> "CA" , "City Population"=>3792621, "State Population" => 1),
               array("City"=>"Chicago", "State"=> "IL" , "City Population"=>2695598, "State Population" => 2),
               array("City"=>"Houston", "State"=> "TX" , "City Population"=>2100263, "State Population" => 400),
               array("City"=>"Philadelphia", "State"=> "PA" , "City Population"=>1526006, "State Population" => 600),
               array("City"=>"Phoenix", "State"=> "AZ" , "City Population"=>1445632, "State Population" => 700),
               array("City"=>"San Antonio", "State"=> "TX" , "City Population"=>1327407, "State Population" => 800),
               array("City"=>"San Diego", "State"=> "CA" , "City Population"=>1307402, "State Population" => 900), 
               array("City"=>"Dallas", "State"=> "TX" , "City Population"=>1197816, "State Population" => 1000),
           array("City"=>"San Jose","State" => "CA", "City Population"=>945942, "State Population" => 1200) 
             ); 


print $cities[0]["State Population"];
//print print_r($cities);


?>

<?php if (count($cities) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($cities))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php //krsort($cities);?>
<?php ///* ------------ >*/ksort($cities[]["State Population"];?>
<?php foreach ($cities as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

0 个答案:

没有答案