Reputation: 427
I want to write data in json file using PHP
like below example but it always adds data outside square brackets(arrays).
How can I write inside the square brackets? Thanks for your help!
Upvotes: 0
Views: 142
Reputation: 11642
You are very close. Modify your code to like below:
$current_data = file_get_contents('users.json');
$array_data = json_decode($current_data, true);
$array_data["users"][] = array ( // -> this line has been changed
'name' => $_POST["name"],
'mobile' => $_POST["mobile"],
'datedon' => $_POST["datedon"]
);
$final_data = json_encode($array_data);
...
Edited:
If you want to add the item to the begin of your array use array-unshift:
...
$array_data = json_decode($current_data, true);
$item = array (
'name' => $_POST["name"],
'mobile' => $_POST["mobile"],
'datedon' => $_POST["datedon"]
);
array_unshift($array_data["users"] , $item);
$final_data = json_encode($array_data);
...
Upvotes: 3
Reputation: 3450
Solution 1
Change your code from this:
$extra[] = array (
'name' => $_POST["name"],
'mobile' => $_POST["mobile"],
'datedon' => $_POST["datedon"]
);
$array_data[] = $extra;
So that it looks something like below:
$array_data['users'][] = array (
'name' => $_POST["name"],
'mobile' => $_POST["mobile"],
'datedon' => $_POST["datedon"]
);
Solution 2
Change the line
$array_data[] = $extra;
to below:
$array_data['users'][] = $extra;
Upvotes: 2