ZgrKARALAR
ZgrKARALAR

Reputation: 489

Json Parsing in Php Foreach

I have one json data but i can't parsing because first type is not have name.

    [
{"id":325,"distance":239,"text":"test","position":{"lat":2,"lon":3}},
{"id":333,"distance":123,"text":"test","position":{"lat":2,"lon":3}},
{"id":331,"distance":1,"text":"test","position":{"lat":2,"lon":3}}
    ]

Php code

$jsonurl = "url address";
$json = file_get_contents($jsonurl);

$obj = json_decode($json,true);

$it = "<ul>"
    foreach ($obj[0] as $list) 
    {
        $it .= "<h4>".$list['id']."</h4>"
    }

Upvotes: 1

Views: 36

Answers (1)

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

Its stdClass Object not an array, so access it like this,

$it .= "<h4>".$list->id."</h4>";

And also change your for loop like this

foreach ($obj as $list) 
            ^ remove [0] here

Finally your loop looks like this,

foreach ($obj as $list) 
{
    $it .= "<h4>".$list->id."</h4>"
}

see demo here

Upvotes: 1

Related Questions