使用PHP获取json数据

时间:2013-11-25 12:49:46

标签: php arrays json

我有一个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
    }
}

4 个答案:

答案 0 :(得分:4)

我相信您跳过了1个节点,请尝试:

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

答案 1 :(得分:4)

这应该有用;

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

在'设备'之前有一个键

答案 2 :(得分: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'];
}

答案 3 :(得分:1)

您无法正确访问json。你需要像这样访问它。

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

试试。