【问题标题】:PHP: How to access array element values using array-index [duplicate]PHP:如何使用数组索引访问数组元素值
【发布时间】:2012-08-29 22:14:35
【问题描述】:

如何使用数组索引访问数组元素值?

<?
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);

echo $arr['dynamic']['pageCount']; // working
echo $arr[0]['pageCount']; // not working
?>

我不知道“动态”中有什么,所以我想动态访问 pageCount 值?

【问题讨论】:

  • foreach 将遍历数组,同时提供键和值。 reset 将返回第一个值而不考虑键(您也可以使用key 获取键)。 array_values 将用自动递增的整数替换键。你的用例到底是什么?

标签: php arrays


【解决方案1】:

array_values 是您要查找的函数

例子:

<?php
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);
echo $arr['dynamic']['pageCount']; // working

$arr = array_values($arr);
echo $arr[0]['pageCount']; // NOW working

?>

【讨论】:

    【解决方案2】:
    $arr = json_decode($json, true);
    foreach ($arr as $key => $value) {
        if (isset($value['pageCount'])) {
            //do something with the page count
        }
    }
    

    如果结构始终是单个嵌套的 JS 对象:

    $obj = current($arr);
    echo $obj['pageCount'];
    

    【讨论】:

    • 好的,开始工作了。但是在想是否有没有循环的直接访问
    • @ShivaramAllva:它可以如此直接以至于它伤害:extract(reset($arr));。正如我在评论中所说——用例是什么?
    • 我已经使用非循环解决方案更新了我的答案,该解决方案仅在结构始终是单个嵌套 JS 对象时才有效,如示例中所示。
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2016-06-09
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多