php - Array parts access -
i'm trying understand arrays better. pardon elementary questions opened first php book 3 weeks ago.
i can retrieve key/value pairs using foreach (or loop) below.
$stockprices= array("google"=>"800", "apple"=>"400", "microsoft"=>"4", "rim"=>"15", "facebook"=>"30"); foreach ($stockprices $key =>$price)
what confused multi dimensional arrays one:
$states=(array([0]=>array("capital"=> "sacramento", "joined_union"=>1850, "population_rank"=> 1), [1]=>array("capital"=> "austin", "joined_union"=>1845,"population_rank"=> 2), [2]=>array("capital"=> "boston", "joined_union"=>1788,"population_rank"=> 14) ));
my first question basic: know "capital', "joined_union", "population_rank" keys , "sacramento", "1850", "1" values (correct?). call [0][1][2]? "main keys" , "capital" etc. sub-keys? can't find definition those; neither in books nor online.
the main question how retrieve arrays [0][1][2]? want array joined_union in 1845 (or trickier during 1800s), remove array.
finally, can name arrays [0][1][2] california, texas , massachusetts correspondingly?
$states=(array("california"=>array("capital"=> "sacramento", "joined_union"=>1850, "population_rank"=> 1), "texas"=>array("capital"=> "austin", "joined_union"=>1845,"population_rank"=> 2), "massachusetts"=>array("capital"=> "boston", "joined_union"=>1788,"population_rank"=> 14) ));
unlike other languages, arrays in php can use numeric or string keys. choose. (this not loved feature of php , other languages sneer!)
$states = array( "california" => array( "capital" => "sacramento", "joined_union" => 1850, "population_rank" => 1 ), "texas" => array( "capital" => "austin", "joined_union" => 1845, "population_rank" => 2 ), "massachusetts" => array( "capital" => "boston", "joined_union" => 1788, "population_rank" => 14 ) );
as querying structure have, there 2 ways
1) looping
$joined1850_loop = array(); foreach( $states $statename => $statedata ) { if( $statedata['joined_union'] == 1850 ) { $joined1850_loop[$statename] = $statedata; } } print_r( $joined1850_loop ); /* array ( [california] => array ( [capital] => sacramento [joined_union] => 1850 [population_rank] => 1 ) ) */
2) using array_filter function:
$joined1850 = array_filter( $states, function( $state ) { return $state['joined_union'] == 1850; } ); print_r( $joined1850 ); /* array ( [california] => array ( [capital] => sacramento [joined_union] => 1850 [population_rank] => 1 ) ) */
-
$joined1800s = array_filter( $states, function ( $state ){ return $state['joined_union'] >= 1800 && $state['joined_union'] < 1900; } ); print_r( $joined1800s ); /* array ( [california] => array ( [capital] => sacramento [joined_union] => 1850 [population_rank] => 1 ) [texas] => array ( [capital] => austin [joined_union] => 1845 [population_rank] => 2 ) ) */
Comments
Post a Comment