Eduardo Sanchez Eduardo Sanchez - 3 months ago 23
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:


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'];


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

And the output is:

array(1) {
  array(1) {
    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: