代码之家  ›  专栏  ›  技术社区  ›  Héctor M.

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

  •  0
  • Héctor M.  · 技术社区  · 7 年前

    我有一个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 回复  |  直到 7 年前