douxie2029 2019-06-11 09:20
浏览 132
已采纳

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

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] => name@gmail.com 
    [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?

  • 写回答

2条回答 默认 最新

  • dqdt45183 2019-06-11 09:29
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度