0

i have json file with array and i want to add array elemnts to that array using php . please advice me to proceed.

here is my existing json file

data.json

{
"12":{"userId":"1","username":"Ss","password":"33"},
"32":{"userId":"1","username":"Ss","password":"33"}
}

my php file

below is my code part which i need to append with my existing json file.

$data[$thisId] = array( 
    'userId'=> $userId, 
    'username'=> $username,
        'password'=> $password, 
          ); 
$json = json_encode($data); 

how can i add this to my json file ? pls advice

: I want to write the data which come from php file into my existing json file

1
  • There is no array in your JSON. Commented Mar 15, 2017 at 16:38

1 Answer 1

5

You have to decode your file to append your datas :

$data = json_decode(file_get_contents('data.json'), true);
$data[$thisId] = array( 
    'userId'=> $userId, 
    'username'=> $username,
    'password'=> $password, 
); 
$json = json_encode($data);
file_put_contents('data.json', $json);
Sign up to request clarification or add additional context in comments.

6 Comments

what i want is to write the content of my php file ($json) in to my data.json file . pls advice
You can use file_put_contents function to write your data.json file. You can see my updated answer ;-)
you code works , but it removes existing json part and keep only the latest . how can i keep all
Can you try with json_decode('data.json', true); please ?
Glad to help you ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.