首页 > 解决方案 > Json解码成php

问题描述

我正在尝试将 API 解码为 PHP。

API EXM

{
"users":[
          {"user":"john",
          "user1":"Tabby",
          "user2":"Ruby",
          "user3":"Silver"}
]
}

倾斜用户 = 0(它是空的)

我尝试使用此代码,但它不起作用(空白页)

<?php
$json = '{ "users"[ {"user":"john", "user1":"Tabby", "user2":"Ruby", "user3":"Silver"}';

$arr = json_decode($json);

echo $arr->users->{0}->user; //blank page
echo $arr->users->user1; //blank page
echo $arr->users->0->user2; //syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in
?>

标签: phpjsonapi

解决方案


$arr->users是一个数组而不是一个对象。因此,如果您将脚本更改为

<?php
$json = '{
"users":[
    {"user":"john",
    "user1":"Tabby",
    "user2":"Ruby",
    "user3":"Silver"}
]
}';

$arr = json_decode($json);
print_r($arr);

echo $arr->users[0]->user,"\n";
echo $arr->users[0]->user1,"\n";
echo $arr->users[0]->user2,"\n";
?>

...输出是...

stdClass Object
(
    [users] => Array
        (
            [0] => stdClass Object
                (
                    [user] => john
                    [user1] => Tabby
                    [user2] => Ruby
                    [user3] => Silver
                )

        )

)
john
Tabby
Ruby

推荐阅读