array_push()期望参数1为带有json文件的数组

时间:2019-06-11 09:20:48

标签: php arrays json

我想将两个数组组合在一起,以便将其添加到json文件中。

我尝试使用array_push(),但我不断收到相同的错误消息,即现有的解码json文件不是数组而是对象。

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

如果我打印$json_decode,我会得到:

stdClass Object ( 
    [name] => name 
    [email] => name@gmail.com 
    [IP] => ::1 
)

,并显示错误消息:

  

array_push()期望参数1为数组,对象位于

如何将json内容转换为数组?

2 个答案:

答案 0 :(得分:0)

如果它告诉您array_push的第一个参数是一个对象,则通过向json_decode($str, true)添加第二个参数,将解码的JSON强制为数组。

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

答案 1 :(得分:0)

不要在json_encode()之前做array_push()

使用true作为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);