## 2016年7月23日土曜日

### PHP - Groups of Data: Working with Arrays(array_key_exists)

Learning PHP: A Gentle Introduction to the Web's Most Popular Language (David Sklar (著)、 O'Reilly Media)のChapter 4.(Groups of Data: Working with Arrays)のExercises 3.(No. 2075)を取り組んでみる。

Exercises 3.(No. 2075)

コード(Emacs)

``` \$locations_and_populations = [['New York', 'NY',8175133], ['Los Angeles', 'CA' , 3792621], ['Chicago', 'IL' , 2695598], ['HOuston', 'TX' , 2100263], ['Philadelphia', 'PA' , 1526006], ['Phoenix', 'AZ' , 1445632], ['San Antonio', 'TX' , 1327407], ['San Diego', 'CA' , 1307402], ['Dallas', 'TX' , 1197816], ['San Jose', 'CA' , 945942]]; \$total = 0; \$state_population_totals = array(); foreach (\$locations_and_populations as \$loc_and_pop) { \$city = \$loc_and_pop[0]; \$state = \$loc_and_pop[1]; \$population = \$loc_and_pop[2]; if (array_key_exists(\$state, \$state_population_totals)) { \$state_population_totals[\$state] += \$population; } else { \$state_population_totals[\$state] = \$population; } \$total += \$population; print "\$city, \$state: \$population\n"; } print "total: \$total\n\n"; foreach (\$state_population_totals as \$state => \$population) { print "\$state: \$population\n"; } ```

```\$ php70 -a < sample3.php
Interactive shell

New York, NY: 8175133
Los Angeles, CA: 3792621
Chicago, IL: 2695598
HOuston, TX: 2100263
Phoenix, AZ: 1445632
San Antonio, TX: 1327407
San Diego, CA: 1307402
Dallas, TX: 1197816
San Jose, CA: 945942
total: 24513820

NY: 8175133
CA: 6045965
IL: 2695598
TX: 4625486
PA: 1526006
AZ: 1445632
\$
```