0

I have the following php script in which I attempt to write a JSON file with contents of an array:

$name = "TEST";
$type = "TEST";
$price = "TEST";

$upload_info = array();
$upload_info = array('name'=>$name,'type'=>$type,'price'=>$price);
$temp_array = json_decode(file_get_contents('upload.json'));
array_push($temp_array, $upload_info);
file_put_contents('items.json', json_encode($temp_array));
$json = json_encode($upload_info);
$file = "items.json";
file_put_contents($file, $json);

This will add the following line to items.json:

{"name":"TEST","type":"TEST","price":"TEST"}

It also gives this error:

PHP Warning:  array_push() expects parameter 1 to be array, null given in /var/www/html/list/add.php on line 13

What I would ideally like to do is to have my script add to specific parts of a json file that looks something like this:

{
"GC": [
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" },
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" }
]
"0": [

]
"10": [

]
"20": [

]
"30": [

]
"40": [

]
"50": [

]
"60": [

]
"70": [

]
"80": [

]
"90": [

]
"100": [

]
"200": [

]
"300": [

]
"400": [

]
"500": [

]
}

Each one of those arrays would hold items (similar to the GC array) after they have been added with add.php. Is this possible? If so, how would I do it?

Is it possible to select specific parts of the json where I would want to add the entries? Is there an easier way to do this? I am just looking for a solution to storing my data without using a database.

1 Answer 1

1

you need to use second parameter true, of json_decode() to get array result, like:

$temp_array = json_decode(file_get_contents('upload.json'), true);
//get the needed values from $temp_array
//create a new array out of it
file_put_contents('items.json', json_encode($your_final_array));
Sign up to request clarification or add additional context in comments.

1 Comment

I still get this error: "PHP Warning: array_push() expects parameter 1 to be array, null given in /var/www/html/list/add.php on line 13"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.