문제

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
     },
    ]
도움이 되었습니까?

해결책

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

$jsonArray[] = ...

or:

array_push($jsonArray, ...

not both.

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top