【问题标题】:JSON - PHP foreach persistant errorJSON - PHP foreach 持续错误
【发布时间】:2015-12-11 23:40:02
【问题描述】:

对此我感到非常沮丧,并且可以使用一些精明的头脑。 我正在构建一个相对简单的 API。 使用 PHP 创建了 stdClass() 和 json_encode。 在主机服务器上,数据完美呼应。 在客户端我得到一个持久的 foreach 无效参数错误。

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

结果(主机)

{"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":""}}

问题: 使用 json_decode 和 foreach 只是想回显数组中的项目。

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

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

主持人:

检查 json_last_error 它返回 0
检查 json_last_error_msg 它返回 No Error

客户:

检查 json_last_error 它返回 4
检查 json_last_error_msg 它返回 语法错误

【问题讨论】:

    标签: php arrays json foreach


    【解决方案1】:

    jsondecode 转换为数组而不是标准类对象

    试试这个 第一个$result = json_decode($object , true);

    然后为您的项目 $varname = $item['muid'];

    与您的代码进行比较测试:

    <?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));
    ?>
    

    【讨论】:

    • json_decode 返回一个对象。除非true 作为第二个参数传递。
    • 他可以通过true作为参数来获取json数据
    • 我确实通过了 TRUE。并使用了 $item["muid"]。还是错误。当我转储时,我得到了 NULL。我只是不明白为什么在客户端会出错,但在主机端不会出错。
    • 这两个json字符串都在一个父级下吗?
    • 它是因为您从请求中获取了 2 组 json 代码,要么拆分它们,要么请求单个 json 字符串,它返回 null 因为那里有 2 个 json 字符串
    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2018-09-22
    • 2018-01-22
    • 2015-07-31
    相关资源
    最近更新 更多