Nobert
Nobert

Reputation: 163

PHP merge JSON with brackets

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

Answers (1)

Nigel Ren
Nigel Ren

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

Related Questions