【问题标题】:Fetch json data using PHP使用 PHP 获取 json 数据
【发布时间】:2013-11-25 12:49:46
【问题描述】:

我有一个 json 文件,我想使用 PHP 显示它的数据。我下面的代码给了我错误,

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}

当我用 $users = $data['user']; 替换第 3 个 LOC 时,它会显示一些带有单个字母的数据,我不知道按哪个顺序。

Data.json 文件包含以下数据

{
"user":
    {
    "id":"#03B7F72C1A522631",
    "user":"test@mail.com",
    "password":"123",
    "email":"test@mail.com",
    "name":"m",
    "creationDate":1385048478,
    "compression":true,
    "imageProfile":"medium",
    "videoProfile":"medium",
    "blockAdvert":true,
    "blockTracking":true,
    "devices":[
        {
        "id":"#13C73379A7CC2310",
        "udid":"cGMtd2luNi4xLV",
        "user":"test@mail.com",
        "creationDate":1385048478,
        "status":"active",
        }, 
        {
        "id":"#FE729556EDD9910D",
        "udid":"C1N1",
        "user":"test@mail.com",
        "creationDate":1385291938,
        "status":"active",
        }]
    },
"status":
    {
    "version":"0.9.5.0",
    "command":"getuser",
    "opf":"json",
    "error":false,
    "code":0
    }
}

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    我相信你跳过了 1 个节点,试试吧:

    $users = $data['user']['devices'];
    

    【讨论】:

      【解决方案2】:

      这应该有效;

      $json = file_get_contents('data.json'); 
      $data = json_decode($json,true);
      $users = $data['user']['devices'];
      foreach($users as $user) {
          echo $user['id'];
          echo $user['user'];
      }
      

      “设备”之前有一键。

      【讨论】:

        【解决方案3】:

        我认为您可能想要显示所有devices 信息,您可以将代码更改为:

        $json = file_get_contents('data.json'); 
        $data = json_decode($json,true);
        
        // change the variable name to devices which is clearer.
        $devices = $data['user']['devices'];
        foreach ($devices as $device)
        {
            echo $device['id'];
            echo $device['user'];
        }
        

        【讨论】:

          【解决方案4】:

          您没有正确访问您的 json。您需要像这样访问它。

          $yourVariable = $data['users']['devices'];
          

          试试看。

          【讨论】:

          • OP 写了$data = json_decode($json,true);,它返回一个数组而不是对象。
          • docs.php.net/json_decode 文档说如果参数 $assoc 为真,它会将对象转换为关联数组。我很确定默认情况下这是错误的,如果我错了,请纠正我。
          • phpriot.com/manual/php/function.json-decode 这个例子展示了如果 $assoc 参数被省略,则默认返回一个对象。
          • 默认为false,但OP显式写为true
          猜你喜欢
          • 2012-09-20
          • 2014-09-29
          • 1970-01-01
          • 1970-01-01
          • 2016-03-31
          • 2015-04-08
          • 2015-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多