如何循环到php对象并拉取属性数据

时间:2015-01-26 20:55:36

标签: php

如果我给出了某个属性值(id),我如何循环到下面的php对象并提取属性值(名称,姓氏,城市,国家/地区)。

$users = (object) array(
    'id' => '753',
    'firstname' => 'trevor',
    'lastname' => 'bean',
    'address' => array(
        (object) array(
            'country' => 'Romania'
            'city' => 'Iasi'
        )
    )
)
         (object) array(
    'id' => '754',
    'firstname' => 'ben',
    'lastname' => 'stone',
    'address' => array(
        (object) array(
            'country' => 'Hungary'
            'city' => 'Budapest'
        )
    )
);

我测试过:

 foreach ($users as $user1) {
        if ($user1->id=== '754') {
          echo $user1->firstname
            break;
        }
    }

它返回trevor - firstname id 753而不是请求的ben的第一个名称id 754

3 个答案:

答案 0 :(得分:1)

您发布的代码无效且无法编译。 我允许自己做出一些假设如何纠正它:

$users = array( (object)array(
    'id' => '753',
    'firstname' => 'trevor',
    'lastname' => 'bean',
    'address' => array(
         (object)array(
            'country' => 'Romania',
            'city' => 'Iasi'
            )
        )
    ),
    (object)array(
        'id' => '754',
        'firstname' => 'ben',
        'lastname' => 'stone',
        'address' => array(
             (object)array(
                'country' => 'Hungary',
                'city' => 'Budapest'
            )
        )
    )
);

foreach ($users as $user1) {
    if ($user1->id=== '754') {
      echo $user1->firstname;
        break;
    }
}

现在它可以按您的要求运作。

请注意,我用数组包装了你的对象。

答案 1 :(得分:0)

我想你想要PHP的get_object_vars()。它将在关联数组中返回对象的可访问(在本例中为public)非静态属性:

foreach (get_object_vars($users) as $user1) {
    if ($user1->id=== '754') {
        echo $user1->firstname;
        break;
    }
}

您还需要修复缺少,; s的多个地方。

答案 2 :(得分:0)

您的PHP有一些明显的语法错误(缺少;,),我认为您希望$users变量是用户对象的数组,而不是对象。您的代码应该看起来像这样:

$users = array(
    (object) array(
        'id' => '753',
        'firstname' => 'trevor',
        'lastname' => 'bean',
        'address' => array(
            (object) array(
                'country' => 'Romania',
                'city' => 'Iasi'
            )
        )
    ),
    (object) array(
        'id' => '754',
        'firstname' => 'ben',
        'lastname' => 'stone',
        'address' => array(
            (object) array(
                'country' => 'Hungary',
                'city' => 'Budapest'
            )
        )
    )
);

foreach ($users as $user1) {
    if ($user1->id=== '754') {
        echo $user1->firstname;
        break;
    }
}

它按预期重新调整ben用户: