duan7772 2014-09-17 01:43
浏览 24
已采纳

无法在json_decode PHP中获取数据

I have a script which Im trying to get values from a json string decoded into array.. i can not seem to access the data.

$userData = json_decode($_GET['userData']);

echo $_GET['userData']; //<--- This line works fine and show the $_GET value

$id = $userData['hottsourceID']; //<-- This line errors
$coins = $userData['coins'];

echo $id;
echo $coins;

Catchable fatal error: Object of class stdClass could not be converted to string in /home/hottsour/public_html/DeadRun/php/AppCreateDRAccount.php on line 11

  • 写回答

2条回答 默认 最新

  • duaeim2874 2014-09-17 01:47
    关注

    By default json_decode will not create associative arrays, instead it will create objects

    $data = json_decode('{"foo":"bar"}');
    
    echo $data->foo;
    // "bar"
    

    If you'd like json_decode to use associative arrays instead, you can pass true as the second argument

    $data = json_decode('{"foo":"bar"}', true);
    
    echo $data["foo"];
    // "bar"
    

    Now that you know this, you can adapt your own solution like so

    $userData = json_decode($_GET["userData"]);
    
    $id = $userData->hottsourceID;
    $coins = $userData->coins;
    
    echo $id;
    echo $coins;
    

    Additional tips

    Since you're parsing user input, you might want to throw an error if the JSON in $_GET["userData"] is invalid. json_decode will return null if parsing failed.

    function decode($json) {
      $data = json_decode($json);
      if (is_null($data)) throw new Exception("Invalid JSON");
      return $data;
    }
    
    try {
      $userData = decode($_GET["userData"]);
      $id = $userData->hottsourceID;
      $coins = $userData->coins;
    
      echo $id;
      echo $coins;
    }
    catch (Exception $e) {
      echo $e->getMessage();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?