简体   繁体   English

如何从Json数组获取值

[英]How to get a value from a Json array

I have a function in php that returns this json array, this is the function 我在php中有一个函数返回此json数组,这是该函数

    $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...)? 我的问题是如何获取值(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 . 令牌的类型是字符串,并且正确使用json_decode

If you try to var_dump the value you will get: 如果尝试使用var_dump值,则会得到:

$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. 您可以看到$obj变量是一个数组,并且它的第一个元素是另一个具有unique_id键的数组。

To get to that you should use: 为此,您应该使用:

$obj[0]['unique_id'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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