Reputation: 163
I have this JSON file:
{"customers": [{"Name": "John Doe", "E-mail": "[email protected]"}]}
And i have this PHP code:
$customers_file = fopen("customers.json", "r");
$customers = json_decode(fread($customers_file ,filesize("customers.json")), true);
fclose($customers_file);
$customer = array("Name" => "Jane Doe", "E-mail" => "[email protected]");
$customers["customers"] += $customer;
$customers_file = fopen("customers.json", "w");
$customers = fwrite($customers_file, json_encode($customers));
fclose($customers_file);
Then the JSON file turns in:
{"customers": [{"Name": "John Doe", "E-mail": "[email protected]"}, "Name": "Jane Doe", "E-mail": "[email protected]"]}
Is there a way i can get:
{"customers": [{"Name": "John Doe", "E-mail": "[email protected]"}, {"Name": "Jane Doe", "E-mail": "[email protected]"}]}
Upvotes: 0
Views: 30
Reputation: 57131
When you add the new item in
$customers["customers"] += $customer;
this is adding the new array data at the wrong level, you need to add it to the customers array instead (using []
)...
$customers["customers"][] = $customer;
You could also have a look into file_get_contents()
and file_put_contents()
to reduce the fopen()
...fclose()
boilerplate code.
Upvotes: 2