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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题