Pergunta

I'm trying to append new items to the end of my json file. When the code runs as below, it keeps appending null instead of the new items. I've searched around and haven't found any solutions yet.

Here's the PHP:

$_POST["carMake"] = 'toyota'; 
$_POST["startProduction"] = '258147369';
$_POST["endProduction"] = '369258147';

$file = "cars.json";
$jsonArray = json_decode(file_get_contents($file), true);
array_push($jsonArray[], array( 'Make' => $_POST["carMake"], 'Start Prod' => $_POST["startProduction"], 'End Prod' => $_POST["endProduction"] ));
file_put_contents($file, json_encode($jsonArray));

$answer = array ( 'Created' => "true", 'validation' => "Car added");
return json_encode($answer);

The intended output is:

    [
     {
      "Make":"Toyota",
      "Start Prod":258147369,
      "End Prod":369147258
     },
     {
      "Make":"BMW",
      "start":789456123,
      "end":159487263
     },
    ]
Foi útil?

Solução

array_push($jsonArray[], ... is wrong. You should either do:

$jsonArray[] = ...

or:

array_push($jsonArray, ...

not both.

Outras dicas

Try this as PHP manual said that. http://www.php.net/manual/en/function.array-push.php

$_POST["carMake"] = 'toyota'; 
$_POST["startProduction"] = '258147369';
$_POST["endProduction"] = '369258147';

$file = "cars.json";
$jsonArray = json_decode(file_get_contents($file), true);
$jsonArray[]= array( 'Make' => $_POST["carMake"], 'Start Prod' => $_POST["startProduction"], 'End Prod' => $_POST["endProduction"] );
file_put_contents($file, json_encode($jsonArray));

$answer = array ( 'Created' => "true", 'validation' => "Car added");
return json_encode($answer);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top