1

I'm currently trying to append all the questions from questions.json to my main PHP page and I would like to do it dynamically.

I've searched for tutorials and when I copy-paste the code it works, but when I change it with mine, it doesn't. I'm still a newbie who is learning, so please don't throw at me bunch of complex code. Much appreciated !

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"}]}
    ]
}

Edit: I tried using this code and currently it isn't echoing anything.

<?php

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

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

?>
Nikola Stoilov
  • 85
  • 1
  • 10

1 Answers1

1

reponses is an array, so you'll have to iterate it to echo the choices:

<?php
foreach($json_a['questions'] as $q) {
    echo "\n\n" . $q['question'] . "\n";
    foreach ($q['reponses'] as $r) {
        echo "\t" . $r['choix'];
    }
}
Jordi Nebot
  • 3,355
  • 3
  • 27
  • 56
  • Ok, I understand what are you doing, but may I ask how can I include the json into the .php file, so the iteration could actually know where to search for the array questions ? I mean for JS is `` How does that work for json ? – Nikola Stoilov Dec 17 '17 at 18:35
  • You can't do that in PHP. What you're doing with `file_get_contents` is fine. – Jordi Nebot Dec 17 '17 at 18:39
  • Alright, I managed to echo all the questions and answers one, but it seems that "\n" isn't being registered at all. Do you know how can I make it to echo all the questions and answers but put before that an and to wrap it up in a
    , so it actually has questions with clickable answers ?
    – Nikola Stoilov Dec 17 '17 at 18:59
  • Sure, @NikolaStoilov :) What you want is to output HTML with PHP. It's one of the most common uses of PHP, so I'd suggest you to read this question and answer. It'll definitely help you achieve what you want: https://stackoverflow.com/q/1100354/1534704 – Jordi Nebot Dec 18 '17 at 08:14