Friday, May 17, 2013

Example Multi Dimensional Array In PHP

Hi ! Multi Dimensional Array or Arrays inside an Array is a basic and useful data structure in PHP. This post is regarding an example which describe you how to declare a multi dimensional array, how to insert data to it, how to print back those elements and how to manipulate those datum.

In this example population amounts in America is categorized into states and to each city. We have to organize them in an array, Print back them and find totals under each states and country.


<?php 
//Multi Dimensional Array
    $population=array(
                            'NY'=>array('New York'=>8008278),
                            'CA'=>array('Los Angeles'=>3694420,'San Diego'=>1223400),
                            'IL'=>array('Chicago'=>2896016),
                            'TX'=>array('Houstan'=>1953631,'Dallas'=>1188580,'San Antonio'=>1144646),
                            'AZ'=>array('Phoenix'=>1321045)
                          
                        );
                  
    $totalStatePopulation=0;                  
    $totalPoupulation=0;
   
    echo('<table border="1" width="400px">');
//$population refers to the above array $state refers to its keys(NY,CA,IL,TX,AZ) $city refers to its values(array('New York'=>8008278),array('Los Angeles'=>3694420,'San Diego'=>1223400),array('Chicago'=>2896016),array('Houstan'=>1953631,'Dallas'=>1188580,'San Antonio'=>1144646),array('Phoenix'=>1321045))
    foreach($population as $state=>$city){
        $totalStatePopulation=0;
      
         //$city is the same variable in the outer loop. So, $name refers to array $city 's keys. $amount is the population amount under each key.
            foreach($city as $name=>$amount){
            echo('<tr>');
//print the keys of the inner arrays
            echo('<td>'.$name.'</td>');
//prints the amounts under inner keys
            echo('<td>'.$amount.'</td>');
            echo('</tr>');
//calculate the state population of the country
            $totalStatePopulation=$totalStatePopulation+$amount;
//calculate the total population of the country
            $totalPoupulation=$totalPoupulation+$amount;
            }
          
          
            echo('<tr>');
//prints the keys of the outer array
            echo('<td>'.$state.'</td>');
            echo('<td style="color:green;font-weight:bold">'.$totalStatePopulation.'</td>');
            echo('</tr>');
    }
   
            echo('<td>Total Population</td>');
            echo('<td style="color:red;font-weight:bold">'.$totalPoupulation.'</td>');
    echo('</table>');


?>

No comments:

Post a Comment