0

我尝试通过 php 读取 json

{
  "data": [
    {
      "id": "3043252fsdgdf36360354", 
      "name": "name1", 
      "access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
    }, 
    {
      "id": "3326848fdgsdfgsdf03424168", 
      "name": "name2", 
      "access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
    }}

我试试这个代码

$sfgsdfg=  $json_a=json_decode($read,true);


echo  $json_a['data'][3043252fsdgdf36360354];
echo  $json_a['3043252fsdgdf36360354'][access_token];

不使用这个 php 代码我需要帮助才能阅读它

我需要通过 3043252fsdgdf36360354 选择 access_token 作为 echo $json_a['data'][3043252fsdgdf36360354]['access_token'];

我只需要按 id 读取。mysql 命令。选择 access_token 其中 id ='3326848fdgsdfgsdf03424168';

4

2 回答 2

1

首先,您的 JSON 缺少一个]字符,将导致json_decode返回 NULL。您应该首先更正 JSON 字符串。您可以使用jsonlint.com等在线服务来验证 JSON。将 JSON 字符串解码为关联数组后,您可以遍历数组并检查其中是否包含给定的 ID。如果是这样,您可以轻松获取相应的访问令牌。

我已经把它变成了一个简短的小功能。您可以使用它通过 ID 获取访问令牌:

$jsonArray = json_decode($str, TRUE);
function getAccessTokenFromID($id, $jsonArray) {
    foreach ($jsonArray['data'] as $k => $elem) {
        if($elem['id'] == $id) {
            $access_token = $elem['access_token'];
        }
    }
    return $access_token;
}

用法:

$myid = '3043252fsdgdf36360354';
$my_accesstoken = getAccessTokenFromID($myid, $jsonArray);

演示!

于 2013-09-18T22:05:48.540 回答
0

不是格式良好的json。尝试:

{
  "data": [
    {
      "id": "3043252fsdgdf36360354", 
      "name": "name1", 
      "access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
    }, 
    {
      "id": "3326848fdgsdfgsdf03424168", 
      "name": "name2", 
      "access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
    }
  ]
}

和 php:

$val = json_decode($read, TRUE);
echo $val['data'][0]['id'];

更新:

function find_by_id($id, $val) {
  foreach($val['data'] as $key => $obj) {
    if ($obj['id'] === $id)
      return $obj['access_token'];
  }
}
于 2013-09-18T21:43:25.627 回答