Здравствуйте у меня следующая проблема
Вот как сейчас выглядит мой сайт;
Я хочу отобразить содержимое в таблице из массива, расположенного в файле JSON.Я хотел сделать это в цикле foreach, и он отлично работает.Пока я не добавлю новый с помощью array_pushПотому что тогда я получаю все виды ошибок
Это добавит новую строку и место для элементов, но они не будут заполнены из-за этих ошибок;
Я точно знаю, что контент добавляется в файл json с моим array_push с точно такими же ключами, но они его не распознают.
Я сам обнаружил, что когда я добавляю что-то в массив, перед ним добавляются «0», «1», «2» и т. д.Когда я сам удаляю номер, он будет работать в таблице, но автоматически будет добавлять его в массив;
"0":{"Aquaman":{"Naam":"Aquaman","Power1":"Water","Power2":"Vissen","Power3":"Zwemmen","Power4":"Onderwater ademen"}}
Как я могу удержать его от этого?Или какие еще есть решения этой проблемы?
PHP/HTML;
<?php
// ========== Read an array from a file ===================
// Open the file in 'read' modus
$file = fopen('myfile.json','r');
// Read the JSON array from the file
$aJSONArray = file_get_contents('myfile.json');
// Convert to JSON array back to a PHP array
$arrDCSuperheroes = json_decode($aJSONArray,TRUE);
// Close the file again
fclose($file);
// ========== Add a new value to the array ==============
if (!empty($_POST)) {
$strSuperheldNaam = $_POST['strSuperheldNaam'];
$arrDCSuperheroes2[$strSuperheldNaam] = array();
$arrDCSuperheroes2[$strSuperheldNaam]['Naam'] = $_POST['strSuperheldNaam'];
$arrDCSuperheroes2[$strSuperheldNaam]['Power1'] = $_POST['strPower1'];
$arrDCSuperheroes2[$strSuperheldNaam]['Power2'] = $_POST['strPower2'];
$arrDCSuperheroes2[$strSuperheldNaam]['Power3'] = $_POST['strPower3'];
$arrDCSuperheroes2[$strSuperheldNaam]['Power4'] = $_POST['strPower4'];
array_push($arrDCSuperheroes, $arrDCSuperheroes2);
var_dump($arrDCSuperheroes);
}
// ========== Saving an array to a file =================
// Use JSON to encode the array into a storeable string
$aJSONArray = json_encode($arrDCSuperheroes);
// Open the file in 'write' modus
$file = fopen('myfile.json','w');
// Save the content of the JSON array into the file
file_put_contents('myfile.json', $aJSONArray);
// Close the file
fclose($file);
echo("
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<table border=1 width='90%'>
<tr><th>Naam</th><th>Power 1</th><th>Power 2</th><th>Power 3</th><th>Power 4</th></tr>
");
foreach($arrDCSuperheroes as $arrDCSuperheroesList) {
echo("<tr><td>".$arrDCSuperheroesList['Naam']."</td><td>".$arrDCSuperheroesList['Power1']."</td><td>".$arrDCSuperheroesList['Power2']."</td><td>".$arrDCSuperheroesList['Power3']."</td><td>".$arrDCSuperheroesList['Power4']."</td></tr>");
}
echo(" </table>
<h3>Toevoegen aan array!</h3><hr>
<form method='post'>
Naam: <input type='text' name='strSuperheldNaam'><br/>
Power 1: <input type='text' name='strPower1'><br/>
Power 2: <input type='text' name='strPower2'><br/>
Power 3: <input type='text' name='strPower3'><br/>
Power 4: <input type='text' name='strPower4'><br/><br/>
<input type='submit' value='SUBMIT!'>
</form>
</body>
</html>
");
?>
Вы не должны использовать array_push
для ассоциативных массивов.
Предполагая, что вы хотите, чтобы ваша структура json была:
{
"heroName": {
"property": "value"
},
...
}
Вам просто нужно добавить нового героя по имени с его свойствами, как показано ниже. Также вы можете переместить логику для сохранения файла внутри оператора if, чтобы убедиться, что файл записывается только при его обновлении, а не при каждой загрузке страницы.
// ...
// Convert to JSON array back to a PHP array
$arrDCSuperheroes = json_decode($aJSONArray,TRUE);
if (!empty($_POST)) {
$strSuperheldNaam = $_POST['strSuperheldNaam'];
$arrDCSuperheroes[$strSuperheldNaam] = [
'Naam' => $_POST['strSuperheldNaam'],
'Power1' => $_POST['strPower1'],
'Power2' => $_POST['strPower2'],
'Power3' => $_POST['strPower3'],
'Power4' => $_POST['strPower4'],
];
// Use JSON to encode the array into a storeable string
$aJSONArray = json_encode($arrDCSuperheroes);
file_put_contents("myfile.json", $aJSONArray);
}
// ...
попробуйте print_r($arrDCSuperheroes);