1

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
     },
    ]

2 Answers 2

1

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

$jsonArray[] = ...

or:

array_push($jsonArray, ...

not both.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly. I didnt see that restriction in the documentation. Thank you for the tip!
0

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);

2 Comments

Tried this as well and it worked too. Thank you for the quick response!
@user2238415 - please search this on documentation page to add one element to the array it's better to use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.