我想更好地理解数组.请原谅我的基本问题,因为我刚刚在三周前打开了我的第一本php书.
我知道您可以使用foreach(或for循环)检索键/值对,如下所示.
$stockprices= array("Google"=>"800", "Apple"=>"400", "Microsoft"=>"4", "RIM"=>"15", "Facebook"=>"30");
foreach ($stockprices as $key =>$price)
Run Code Online (Sandbox Code Playgroud)
令我困惑的是像这样的多维数组:
$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)
));
Run Code Online (Sandbox Code Playgroud)
我的第一个问题非常基本:我知道"大写","joined_union","population_rank"是关键,"萨克拉门托","1850","1"是值(正确吗?).但你怎么称呼[0] [1] [2]?它们是"主键"和"大写"等子键吗?我找不到任何定义;无论是在书中还是在线.
主要问题是如何检索数组[0] [1] [2]?假设我想在1845年获得join_union的数组(或者在19世纪更加棘手),然后删除该数组.
最后,我可以将Arrays [0] [1] [2]命名为加利福尼亚州,德克萨斯州和马萨诸塞州吗?
$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)
));
Run Code Online (Sandbox Code Playgroud)
与其他语言不同,PHP 中的数组可以使用数字或字符串键。你选。(这不是PHP的一个深受喜爱的特性,其他语言嗤之以鼻!)
$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
)
);
Run Code Online (Sandbox Code Playgroud)
至于查询你拥有的结构,有两种方法
1)循环
$joined1850_loop = array();
foreach( $states as $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
)
)
*/
Run Code Online (Sandbox Code Playgroud)
2)使用array_filter函数:
$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
)
)
*/
Run Code Online (Sandbox Code Playgroud)
-
$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
)
)
*/
Run Code Online (Sandbox Code Playgroud)