php – 数组部件访问
发布时间:2020-05-25 09:00:26 所属栏目:PHP 来源:互联网
导读:我想更好地理解数组.请原谅我的基本问题,因为我刚刚在三周前打开了我的第一本php书. 我知道您可以使用foreach(或for循环)检索键/值对,如下所示. $stockprices= array(Google=800, Apple=400, Microsoft=4, RIM=15, Facebook=30);foreach ($stock
|
我想更好地理解数组.请原谅我的基本问题,因为我刚刚在三周前打开了我的第一本php书. 我知道您可以使用foreach(或for循环)检索键/值对,如下所示. $stockprices= array("Google"=>"800","Apple"=>"400","Microsoft"=>"4","RIM"=>"15","Facebook"=>"30");
foreach ($stockprices as $key =>$price)
令我困惑的是像这样的多维数组: $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)
));
我的第一个问题非常基本:我知道“大写”,“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","Texas"=>array("capital"=> "Austin","Massachusetts"=>array("capital"=> "Boston","population_rank"=> 14)
));
与其他语言不同,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
)
);
至于查询你所拥有的结构,有两种方法 $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
)
)
*/
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
)
)
*/
– $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
)
)
*/ (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
