Eduardo Sanchez Eduardo Sanchez - 3 days ago 5
PHP Question

How to get a value from a Json array

I have a function in php that returns this json array, this is the function

$token = $db->getTokenFromEmail($email);
echo $token;


and this is what i get:

[{"unique_id":"cBuJ-xsDDAo:APA91bHYgPwuwXGVxNMuW_Xs0u5bvbr_QSJq8G1_tZ-nGHOdRB0Nv5ijb2BcaP_wUkpyxwERo7cuQxj89YHjOZdIeIwBOGyeHMP_Ywkg_mocfZQr-CxOzy41i8GKj3X6WFjLZJU4ZcbK"}]


My question is how can I get the value (cBuJ-xsD...)?
I have tried this but it doesn't work

$obj = json_decode($token,true);
echo $obj['unique_id'];

Answer

Your token's type is a string, and you are correct to use json_decode.

If you try to var_dump the value you will get:

$token = '[{"unique_id":"cBuJ-xsDDAo:APA91bHYgPwuwXGVxNMuW_Xs0u5bvbr_QSJq8G1_tZ-nGHOdRB0Nv5ijb2BcaP_wUkpyxwERo7cuQxj89YHjOZdIeIwBOGyeHMP_Ywkg_mocfZQr-CxOzy41i8GKj3X6WFjLZJU4ZcbK"}]';
$obj = json_decode($token,true);
var_dump($obj);

And the output is:

array(1) {
  [0]=>
  array(1) {
    ["unique_id"]=>
    string(152) "cBuJ-xsDDAo:APA91bHYgPwuwXGVxNMuW_Xs0u5bvbr_QSJq8G1_tZ-nGHOdRB0Nv5ijb2BcaP_wUkpyxwERo7cuQxj89YHjOZdIeIwBOGyeHMP_Ywkg_mocfZQr-CxOzy41i8GKj3X6WFjLZJU4ZcbK"
  }
}

You can see that the $obj variable is an array, and it's first element is another array that has the unique_id key.

To get to that you should use:

$obj[0]['unique_id'];
Comments