How to edit json file with php

时间:2019-04-16 22:28:06

标签: php arrays json object

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!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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;