Pergunta

I have this PHP code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$jsondata = curl_exec($ch);
if (curl_error($ch)) 
    die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));

curl_close($ch);

$arr = json_decode($jsondata);
echo "\nResponse: ".htmlentities($jsondata)."\n\nArray: ".print_r($arr,true);

Which outputs:

Response: {"result":"success","clientid":83} Array: 
stdClass Object ( [result] => success     [clientid] => 83 )

I want to grab the value 83 stored in the variable called $clientid.

But I can't figure out how to do it.

Foi útil?

Solução

You are confusing a PHP object with a PHP array.

You should be doing this: echo $arr->clientid;

Example 1, access a value of an object like this:

<?php 
  $jsondata = '{"firstName":"John", "lastName":"Doe"}';
  $arr = json_decode($jsondata);

  echo gettype($arr);
  echo $arr->firstName;
?>

This prints:

object
John

Example 2, access a value of an array like this:

<?php 
  $yarr = array(5,6,7);
  echo $yarr[0];
?>

This prints:

5

Outras dicas

Your main mistake is assuming json_decode returns an array.

$arr = json_decode($jsondata);

Will set up $arr as an object. If you wanted to access it as an array, you can do this:

$arr = json_decode($jsondata, TRUE);

The extra parameter on the end tells json_decode to return an array instead of an object. Then you could do:

echo $arr["clientid"];

try echo $arr["clientid"] to get data from array

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top