1

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?

1
  • 1
    $json_decode = json_decode($old_json, true); to get the Json as an array Commented Jun 11, 2019 at 9:28

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@FrisoStolk glad to help you :):)
0

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

Comments

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.