【问题标题】:Iterating Through JSON Objects遍历 JSON 对象
【发布时间】:2015-01-11 17:54:46
【问题描述】:

我为新手的问题道歉,但我正在尝试 我正在尝试遍历 JSON 数据而不列出其中的特定对象。

我先指定 JSON 数据

$data = '{
  "question":[{
    "gender":"Both",
    "category":"Finance",
    "question_title":"Will the German Economy Collapse",
    "country":"Lebanon"
    }]
}';

然后我正在解码 $data

$jsonDecoded = json_decode($data);

然后我尝试遍历解码后的 JSON 变量:

foreach ($jsonDecoded->question as $object){
    print $object;
}

但我收到以下错误:

Catchable fatal error: Object of class stdClass could not be converted to string

关于我哪里出错的任何指针?谢谢。

【问题讨论】:

  • 正如错误所说:你不能print一个对象。试试var_dump($object)print $object->gender
  • 啊,谢谢,我没想到错误是由于实际打印造成的。

标签: php json iterator


【解决方案1】:
    <?php
$data = '{
  "question":[{
    "gender":"Both",
    "category":"Finance",
    "question_title":"Will the German Economy Collapse",
    "country":"Lebanon"
    }]
}';
$jsonDecoded = json_decode($data);
foreach ($jsonDecoded->question as $object){
    print_r ($object);
}
?>

喜欢这个

【讨论】:

    猜你喜欢
    • 2015-09-26
    • 2017-06-23
    相关资源
    最近更新 更多