【问题标题】:Echo Multidimensional json and phpEcho 多维 json 和 php
【发布时间】:2017-09-10 12:26:16
【问题描述】:

我正在尝试访问具有多维 json 输入的 API,这是数组

[{
"Value 1":"a",
"Value 2":
    {
        "Value 3":
        {
            "Value4":11,
            "Value5":"C",
        },
        "Value 4":
        {
            "Value6":12,
        }
    }
}]

我想在 Value4 中回显“11”,在 Value6 中回显“12”。我试着回应它

$varkota = 'url to json output';
$datakota = json_decode(file_get_contents($varkota, true));
$data1 = json_decode($datakota[0]->Value2);
$data2 = json_decode($data1[0]->Value3);
echo $data2[0]->Value4;

错误告诉我:

 ! ) SCREAM: Error suppression ignored for
( ! ) Warning: json_decode() expects parameter 1 to be string, object given in debug.php on line 6
Call Stack
#   Time    Memory  Function    Location
1   0.0020  145280  {main}( )   ..\debug.php:0
2   4.1329  188648  json_decode ( ) ..\debug.php:6

( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Trying to get property of non-object in debug.php on line 7
Call Stack
#   Time    Memory  Function    Location
1   0.0020  145280  {main}( )   ..\debug.php:0

( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Trying to get property of non-object in on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0020  145280  {main}( )   ..\debug.php:0

有什么想法吗?

【问题讨论】:

  • 我无法验证你的 json 字符串 Error: Parse error on line 6: ... "Value5": "C", }, "Value 4": { ----------------------^ Expecting 'STRING', got '}'
  • @RohanKumar 已编辑
  • @YudhistiraBayu json 中有错误。 "Value5":"C",最后一个键不能有逗号。
  • @YudhistiraBayu 您的 json 无效(检查 jsonlint.com)尝试我更新的答案并使用有效的 json 进行演示。

标签: php arrays json multidimensional-array


【解决方案1】:

首先,您只需要使用一次json_decode,并且您的键有空格,而有空格的键则需要将其作为字符串括在{} 中。试试吧,

$datakota = json_decode(file_get_contents($varkota, true));
$data1 = $datakota[0]->{'Value 2'};
$data2 = $data1->{'Value 3'}; // no need to use array [0], as Value 2 is object
echo $data2->Value4; // no need to use array [0], as Value 3 is also an object

在一行中,直接作为

echo $datakota[0]->{'Value 2'}->{'Value 3'}->Value4;

Online Demo

【讨论】:

    【解决方案2】:

    您只需拨打json_decode 一次。

    $varkota = 'url to json output';
    $datakota = json_decode(file_get_contents($varkota, true));
    $data1 = $datakota[0]->Temperature->Metric;
    // ...
    

    或者使用你当前的 json 字符串

    $data1 = $datakota[0]->{"Value 2"}->{"Value 3"};
    

    【讨论】:

    • 我认为问题开启者没有任何好处,但我为改变的结构添加了一个替代方案..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多