dtpa98038 2019-02-01 09:59
浏览 77
已采纳

将元素添加到关联数组会引发错误 - php

I have an json-encoded array in my database which I like to add elements to. The json from the database looks like this:

{"1549006986":"a27f51b4dba8899c7a278465a873449a"}

Here is the code with which I want to add the element:

$tokenarray = json_decode($_SESSION['logintoken']);

$counttokens = count($tokenarray);

$newtoken = md5(mt_rand());

$datetime = $_SERVER['REQUEST_TIME'];

if ($counttokens < 6){

    $tokenarray += [$datetime => $newtoken];

    }

$tokenarrayjson = json_encode($tokenarray);

But this line

$tokenarray += [$datetime => $newtoken];

ends up in this error:

Fatal error: Uncaught Error: Unsupported operand types in **SITEURL** Stack trace: #0 {main} thrown in **SITEURL** on line

Can someone tell where im wrong here? From another post on this site, adding elements like this to an array should be valid from php version 5.4. I run on 7.2

Regards andreas

  • 写回答

3条回答 默认 最新

  • douche1936 2019-02-01 10:55
    关注

    Your problem is your call to json_decode. Because you have not passed the second parameter as true, it is returning an object, which you are then attempting to use as an array, causing the errors you are seeing. If you had put a print_r($tokenarray); in your code after the json_decode, you would have seen this:

    stdClass Object ( 
        [1549006986] => a27f51b4dba8899c7a278465a873449a
    )
    

    To fix it, change:

    $tokenarray = json_decode($_SESSION['logintoken']);
    

    to

    $tokenarray = json_decode($_SESSION['logintoken'], true);
    

    You also have a typo in your code,

    newtoken = md5(mt_rand());
    

    should be

    $newtoken = md5(mt_rand());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号