将Json问题附加到html

问题描述 投票:1回答:1

我目前正试图将questions.json的所有问题附加到我的主要PHP页面,我想动态地进行。

我已经搜索了教程,当我复制粘贴代码时,它可以工作,但是当我用我的代码更改它时,它没有。我还是一个正在学习的新手,所以请不要向我抛出一堆复杂的代码。非常感激 !

questions.json:

{"Theme": "Montpellier",
    "url" : "correction.php",
    "questions": [ 
        {"question": " Combien sommes-nous?", "reponses": [{"choix": "3"},{"choix": "43"},{"choix": "5"}]},
        {"question": "Selon sa demographie quelle est le classement de Montpellier?","reponses": [{"choix": "8eme"},{"choix": "5eme"},{"choix": "2eme"}]},
        {"question": "Autour de quelle date la fête des lumières ce deroulle-t-elle? ","reponses": [{"choix": "31 Novembre"},{"choix": "6 Septembre"},{"choix": "18 Juillet"}]},
        {"question": " Combien de lignes de trameway y'a t-il à Montpellier?","reponses": [{"choix": "4"},{"choix": "5"},{"choix": "2"}]},
        {"question": "Quelle est le plus grand Campus de Montpellier? ","reponses": [{"choix": "fac des sciences"},{"choix": "fac d'economie"},{"choix": "fac de droit"}]},
        {"question": "Quelle est la place la plus vivante à Montpellier?","reponses": [{"choix": "Comedie"},{"choix": "Gare Saint-Roch"},{"choix": "Peyrou"}]}
    ]
}

编辑:我尝试使用此代码,目前它没有回应任何东西。

<?php

$string = file_get_contents("questionnaire.json");
$json_a = json_decode($string, true);

foreach ($json_a as $question => $reponses) {
    echo $reponses['choix'];
}

?>
php html json
1个回答
1
投票

响应是一个数组,所以你必须迭代它以回应选择:

<?php
foreach($json_a['questions'] as $q) {
    echo "\n\n" . $q['question'] . "\n";
    foreach ($q['reponses'] as $r) {
        echo "\t" . $r['choix'];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.