Reputation: 81
I want to combine two array's together so I can add that to a json file what already exists.
I've tried to use array_push() but I keep getting the same error that the existing decoded json file is not an array but an object.
$new_user = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'IP' => getUserIpAddr()
];
$myJSON = json_encode($new_user);
$old_json = file_get_contents("players.json");
$json_decode = json_decode($old_json);
array_push($json_decode, $new_user);
print_r($json_decode);
$json_file = fopen('players.json', 'w');
fwrite($json_file, json_encode($json_decode));
fclose($json_file);
If I print the $json_decode
I get this:
stdClass Object (
[name] => name
[email] => [email protected]
[IP] => ::1
)
with the error message:
array_push() expects parameter 1 to be array, object given in
how do I turn the json content into a array?
Upvotes: 1
Views: 252
Reputation: 72299
don't do json_encode()
before array_push()
Use true
as second parameter to json_decode()
$new_user = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'IP' => getUserIpAddr()
];
//$myJSON = json_encode($new_user); not needed
$old_json = file_get_contents("players.json");
$json_decode = json_decode($old_json,true); // true as second parameter
array_push($json_decode, $new_user); // push array not json_encoded value
print_r($json_decode);
$json_file = fopen('players.json', 'w');
fwrite($json_file, json_encode($json_decode));
fclose($json_file);
Upvotes: 1
Reputation: 94662
If it is telling you that the first param to array_push
is an object then force your decoded JSON into an array by adding a second parameter to the json_decode($str, true)
$new_user = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'IP' => getUserIpAddr()
];
//$myJSON = json_encode($new_user);
$old_json = file_get_contents("players.json");
// CHANGED HERE
//$json_decode = json_decode($old_json);
$json_decode = json_decode($old_json, true);
array_push($json_decode, $new_user);
print_r($json_decode);
$json_file = fopen('players.json', 'w');
fwrite($json_file, json_encode($json_decode));
fclose($json_file);
Upvotes: 0