访问多维PHP数组中的值

时间:2013-08-28 21:50:55

标签: php xml arrays json

将我的JSON解码为数组并在其上使用print_r后,我看到以下输出:

Array
(
    [users] => Array
        (
            [0] => Array
                (
                    [id] => 197849982
                    [url] => https://somewhere.zendesk.com/api/v2/users/197849982.json
                    [name] => Some User
                    [created_at] => 2012-04-15T00:38:33Z
                    [updated_at] => 2012-06-08T07:53:03Z
                    [time_zone] => Sydney
                    [email] => email@email.com
                    [phone] => 
                    [photo] => 
                    [locale_id] => 1
                    [locale] => en-US
                    [organization_id] => 21520772
                    [role] => admin
                    [verified] => 1
                    [external_id] => 
                    [tags] => Array
                        (
                        )

                    [alias] => 
                    [active] => 1
                    [shared] => 
                    [shared_agent] => 

有更多输出,但我已将其截断。

我需要访问诸如'id'和'name'之类的值并将它们放入变量中,但我无法弄清楚如何在该数组中找到它们。我尝试了几种方法,每次都会遇到不同的错误。

如何访问此阵列中的数据?

2 个答案:

答案 0 :(得分:0)

这是你的意思吗?

$id = $data['users'][0]['id']

我认为你将拥有多个用户,所以我会做类似

的事情
$users = array();
foreach($data['users'] as $user){
  $users[$user['id']] = $user['name'];
}

答案 1 :(得分:0)

假设您在该结果集中只有一个用户:

$user = $arr['users'][0];

$id = $user['id'];
$name = $user['name'];

如果你有更多,你想循环它们,那么:

$users = $arr['users'];

foreach($users as $user){
    $id = $user['id'];
    $name = $user['name'];

    // Do something with each user here
}