简体   繁体   中英

JSON - PHP foreach persistant error

Am quite frustrated with this and could use some savvy minds. Am building a relatively simple API. Using PHP have created the stdClass()'s and json_encode. On the host server the data echos perfectly. On the client side am getting a persistent foreach invalid argument error.

$thefez= new stdClass();
$thefez->muid=$id;
$thefez->bandname=$bandname;
$thefez->core=new stdClass();
   $thefez->core->joined=$since;
   $thefez->core->bandbio=$bio;
   $thefez->core->genre=$genre;
   $thefez->core->subgenre=$subgenre;

 echo json_encode($thefez);

The Result (Host)

{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":  
{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues",
"subgenre":"Dixie Rhythm"}}

{"muid":"IMA3YNBKZQDNR9RBCSRI","bandname":"Frankie Storm","core":  
{"joined":"Sat 21 February 2015","bandbio":"Just registered. Bio coming soon.","genre":"Popular","subgenre":""}}

ISSUE: Using json_decode and foreach simply want to echo the items in the array.

json_decode(file_get_contents('http://api.mutrs.me/?artists'), TRUE);

foreach($result as $item){
$item->muid;
}

Host:

Checked json_last_error it returns 0
Checked json_last_error_msg it returns No Error

Client:

Checked json_last_error it returns 4
Checked json_last_error_msg it returns Syntax Error

jsondecode converts to array not an standard class object

try this first $result = json_decode($object , true);

then for your item $varname = $item['muid'];

Test this compared to Your Code:

<?php
$data = '{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues","subgenre":"Dixie Rhythm"}}';
var_dump(json_decode($data , true));
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM