【问题标题】:Parsing nested JSON with PHP用 PHP 解析嵌套的 JSON
【发布时间】:2013-07-17 21:00:12
【问题描述】:
{
    "listing": {
        "@attributes": {
            "domain": "example.com"
        },
        "tld": "com",
        "sld": "example",
        "owner": "John Smith"
    }
}

我需要遍历这个 JSON 数组并将值放入 PHP 变量中,以便我可以返回这些值。

例子:

echo $sld;

将打印:

example

我是否需要使用 foreach 循环来执行此操作(如果需要,我将如何格式化)或者是否有一个简单的内置函数,例如 extract() 可以做到这一点?

【问题讨论】:

  • 你可以使用echo $obj->listing->sld;
  • 您是否考虑过使用 json_decode 解码 JSON?如果你传递可选的true boolean 第二个参数,它会将 JSON 转换为一个可以用 PHP 轻松操作的关联数组。

标签: php json parsing foreach


【解决方案1】:
<?php 
$json = '{
    "listing": {
        "@attributes": {
            "domain": "example.com"
        },
        "tld": "com",
        "sld": "example",
        "owner": "John Smith"
    }
}';

$decoded_array = json_decode($json, true);
echo $decoded_array['listing']['sld'];//example
?> 

【讨论】:

    【解决方案2】:

    你可以使用

    json_decode('your json string', true);
    

    这将返回您的字符串的关联数组,然后您可以循环。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多