gpt4 book ai didi

php - 数组部分访问

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:40 27 4
gpt4 key购买 nike

我正在尝试更好地理解数组。请原谅我的初级问题,因为我三周前刚刚打开我的第一本 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)
));

我的第一个问题非常基础:我知道“capital”、“joined_union”、“population_rank”是键,“Sacramento”、“1850”、“1”是值(正确吗?)。但是你怎么称呼[0][1][2]?它们是“主键”和“大写字母”等子键吗?我找不到这些的任何定义;无论是在书上还是在网上。

主要问题是如何检索数组 [0][1][2]?假设我想获取 1845 年加入_union 的数组(或者在 1800 年代甚至更棘手),然后删除该数组。

最后,我可以将数组 [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)
));

最佳答案

与其他语言不同,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
)
);

至于查询你拥有的结构,有两种方式
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
)

)
*/

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
)

)
*/

关于php - 数组部分访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com