【问题标题】:How would I go about traversing this JSON object?我将如何遍历这个 JSON 对象?
【发布时间】:2016-11-13 02:42:08
【问题描述】:

如何访问位于下方的 [0] -> Array() 并通过遍历数组来检索“千与千寻”的 [title]?

Array
(
     [@attributes] => Array
    (
        [version] => 2.0
    )

[channel] => Array
    (
        [title] => Site Title
        [link] => site/
        [language] => en-us
        [category] => All
        [image] => Array
            (
                [title] => Site
                [url] => http://example.com
                [link] => example.com
            )

        [item] => Array
            (
                [0] => Array
                    (
                        [title] => Spirited Away
                        [pubDate] => date
                        [category] => Movies
                        [link] => linkhere
                        [enclosure] => Array
                            (
                                [@attributes] => Array
                                    (
                                        [url] => someurlhere
                                        [length] => length
                                        [type] => application/x-bittorrent
                                    )

                            )

我目前正在尝试使用 foreach 循环遍历数组,但它没有输出任何内容。我会发布我的代码,但这个问题的代码部分已经太长了。我正在使用 PHP,到目前为止我没有尝试过任何工作。

此 JSON 代码是使用 json_encode 从 XML 文档生成的,然后使用 json_decode 解码为 JSON 对象。

【问题讨论】:

  • echo $array['channel']['item'][0]['title'];
  • foreach ( $array['channel']['item'] as $x){echo $x['title'];)
  • 将 JSON 字符串添加到您的问题中总是一个好主意。然后人们就可以对他们的答案进行真正的测试

标签: php json object


【解决方案1】:

评论回答正确。

循环遍历这个特定的数组结构:

foreach ( $array['channel']['item'] as $x){
    echo $x['title'];
}

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2023-04-08
    • 2021-11-20
    • 2019-06-07
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多