遍历JSON元素并获取其值时出错

时间:2019-04-28 00:38:20

标签: php arrays json foreach

我有一个类似这样的JSON文件...

{
    ...{
     },
    "notifications": {
        "satisfactory_record":"satisfactory record",
        "invalid_token" : "Invalid Token",
        ...
    },
    "faq": {
        "title" : "Frequently asked questions",
        "questions": [
            {
                "title" : "What is...?",
                "content" : "This is..."
            },
            {
                "title" : "What is...?",
                "content" : "This is..."
            },
            {
                "title" : "What is...?",
                "content" : "This is..."
            },
            ...
        ]
    }
}

好吧,我想获取对象"faq"并使用循环或迭代器在"questions"的页面上打印faq.php的标题和内容:

<?php

echo "<ul>";

$json = json_decode(file_get_contents('file.json'), true); // Array
$questions = $json['faq']['questions'];

foreach($questions as $question){

    echo "<li>";
    echo "<span>$question['title']</span>";
    echo "<p>$question['content']</p>";
    echo "</li>";
}

echo "</ul>";

?>

但是它不起作用,因为它引发了以下错误: Warning: Invalid argument supplied for foreach()

这是我想要的结果:

enter image description here

  

注意:我通过集体协议使用关联数组而不是对象,请不要回答告诉我将JSON转换为对象而不是数组。

0 个答案:

没有答案