Мне требуется вывести из json формата данные в таблицу, но почему то выводится только последний элемент массива.
Форма обработки
<?php
switch(true) {
case $_POST["name"] == "" && $_POST["number"] == "":
echo "error_name_and_number";
break;
case $_POST["name"] == "":
echo "error_name";
break;
case $_POST["number"] == "":
echo "error_number";
break;
}
if($_POST["name"] != "" && $_POST["number"] != "") {
$file = "data.json";
$arr = ["name"=> $_POST['name'], "number" => $_POST["number"], "date" => date("Y-m-d"), "time" => date("G-i")];
if(!file_get_contents($file)) {
$fp = fopen($file, "w");
$enc = json_encode($arr);
fwrite($fp, "[".$enc."]");
fclose($fp);
} else {
$f = file_get_contents($file);
$fp = fopen($file, "w");
$jsdec = json_decode($f, true);
$merg = array_merge($jsdec, $arr);
$enc1 = json_encode($merg);
fwrite($fp, "[".$enc1."]");
fclose($fp);
}
}
?>
Страница со списком
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>table</title>
</head>
<body>
<table border="1">
<tr>
<td>Имя</td>
<td>Номер</td>
<td>Дата</td>
<td>Время</td>
</tr>
<?php
$f = file_get_contents("data.json");
$dec = json_decode($f, true);
foreach($dec as $val) {
echo "<tr>";
echo "<td>".$val["name"]."</td>";
echo "<td>".$val["number"]."</td>";
echo "<td>".$val["date"]."</td>";
echo "<td>".$val["time"]."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
В таком формате json сохраняется форма
[{
"0": {
"0": {
"name": "1",
"number": "123",
"date": "2021-05-05",
"time": "13-37"
},
"name": "2",
"number": "123",
"date": "2021-05-05",
"time": "13-37"
},
"name": "3",
"number": "123",
"date": "2021-05-05",
"time": "13-37"
}]