doushaqing7080
doushaqing7080
2016-02-23 12:20

如何从json_decode返回特定数据

已采纳

I'm accessing data from an API using json_decode. The code I have returns the array of ALL the date (see below), but I want to return specific data such as 'name' or 'locale'.

$json_string = 'http://api.duedil.com/open/search?q=Surfing%20Sumo&api_key=THE-API-KEY';
          $jsondata = file_get_contents($json_string);
          $obj = json_decode($jsondata,true);
          echo '<pre>';
          var_dump($obj);

This is what is returned (this is abbreviated to save space here):

array(1) {
  ["response"]=>
  array(2) {
    ["pagination"]=>
    string(79) "http://api.duedil.com/open/search?query=Duedil&total_results=6&limit=5&offset=5"
    ["data"]=>
    array(5) {
      [0]=>
      array(4) {
        ["company_number"]=>
        string(8) "06999618"
        ["locale"]=>
        string(14) "United Kingdom"
        ["name"]=>
        string(14) "Duedil Limited"
        ["uri"]=>
        string(51) "http://api.duedil.com/open/uk/company/06999618.json"
      }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douzhan1994 douzhan1994 5年前

    You could just use

    $name = $obj['response']['data'][0]['name'];
    $locale = $obj['response']['data'][0]['locale'];
    

    if you have multiple return values, you could loop over them

    foreach ($obj['response']['data'] as $item) {
        $name = $item['name'];
        $locale = $item['locale'];
    }
    
    点赞 评论 复制链接分享
  • dongpu42006096 dongpu42006096 5年前

    try this sample code:

     <?php
    $data =  isset($obj['response']['data'])?$obj['response']['data']:FALSE;
    
    if(is_array($data))
    {
       foreach ($data as $value) {
        echo $value['name'];
        echo $value['locale'];
    } 
    }
    
    点赞 评论 复制链接分享