简体   繁体   中英

Can not get to data in 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

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();
}

You should make it array by second parameter as true . Without true parameter $userData is object. So you can't access it using $userData['index'] . Try

$userData = json_decode($_GET['userData'], true);
echo $_GET['userData']; 
$id = $userData['hottsourceID'];
$coins = $userData['coins'];

echo $id;
echo $coins;

If you do not use true as second parameter in json_decode() then you can access by $id = $userData->hottsourceID , $coins = $userData->coins and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM