Yudhistira Bayu
Yudhistira Bayu

Reputation: 293

Echo Multidimensional json and php

I'm trying to accessing an API that has json input with multi dimensional, this is the array

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

I want to echo the "11" in Value4 and "12" in Value6. I've try to echo it

$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;

error told me:

 ! ) 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

Any idea?

Upvotes: 2

Views: 1029

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Firstly, you need to use json_decode only once, and your keys are having spaces and the keys which are having spaces then you need to enclose it as string and in {}. Try it like,

$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

In a single line, just use it as

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

Online Demo

Upvotes: 3

Philipp
Philipp

Reputation: 15629

You just have to call json_decode one time.

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

Or with your current json string

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

Upvotes: 1

Related Questions