php – 数组部件访问

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 数组部件访问脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想更好地理解数组.请原谅我的基本问题,因为我刚刚在三周前打开了我的第一本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
    )
);

至于查询你所拥有的结构,有两种方法
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 – 数组部件访问全部内容,希望文章能够帮你解决php – 数组部件访问所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。