Jan 10, 2021
0
Level 6
increment array index by clicking a button in PHP / JS
I would like to increment an array index through a button named next ?
I upload my json data.json:
[
{
"id": 1,
"name": "Survey",
"distance": 5,
"questions": [
{
"id": 1,
"question": "select warm colors ?",
"answer": [
{
"a": "red",
"b": "blue",
"c": "orange"
}
],
"correct": "a,c"
},
{
"id": 2,
"question": "select cool colors ?",
"answer": [
{
"a": "yellow",
"b": "blue",
"c": "green",
"d": "purple"
}
],
"correct": "b,c"
},
{
"id": 3,
"question": "What is a class in PHP?",
"answer": [
{
"a": "A repository for storing key-value pairs.",
"b": "A blueprint from which objects are created.",
"c": "A group of related methods with empty bodies.",
"d": "I don't know, and am not ready for this quiz."
}
],
"correct": "b"
}
]
}
]
then in my php file I load the json file which I convert to array
in survey.php :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="h-screen overflow-hidden flex items-center justify-center" style="background: #edf2f7;">
<div class="bg-gray-100 pt-10">
<div class="mx-auto max-w-6xl">
<div class="p-2 bg-gray-100 rounded">
<div class="flex flex-col md:flex-row">
<div class="md:w-2/3">
<div class="p-4">
<div class="mb-2">
<?php
$strJsonFileContents = file_get_contents("data.json");
//var_dump($strJsonFileContents->distance);
$array = json_decode($strJsonFileContents, true);
//var_dump($array[0]['questions'][0]);
?>
<div class="font-medium rounded-sm text-lg px-2 py-3 flex text-gray-800 flex-row-reverse mt-2 cursor-pointer text-black bg-white hover:bg-white">
<div class="flex-auto mt-8">
<div class="flex flex-col items-center justify-center ">
<?php echo $array[0]['questions'][0]['question']; ?>
</div>
<div class="mt-2">
<div class="bg-white">
<div class="flex flex-col items-left justify-left">
<div class="flex flex-col">
<?php
foreach($array[0]['questions'][0]['answer'][0] as $key=>$value){ ?>
<label class="inline-flex items-left mt-8 ml-6">
<input id="<?php $key; ?>" type="checkbox" class="form-checkbox h-5 w-5 text-gray-600"><span class="ml-2 text-gray-700"><?php echo $value; ?></span>
</label>
<?php } ?>
</div>
</div>
<div class="float-right mt-8 mb-8">
<a href="" class="bg-blue-500 rounded-lg font-bold text-white text-center px-4 py-3 transition duration-300 ease-in-out hover:bg-blue-600 mr-6">
NEXT
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
basically I would like to iterate on the following variables at the click of the NEXT button:
$array[0]['questions'][$increment]['answer'][0]
$array[0]['questions'][$increment]['question'][0]
Please or to participate in this conversation.