PHP多数组获取值

时间:2014-11-02 21:04:34

标签: php arrays variables

如何获得多数组的值。 所以我需要我的数组[user_login]和我的[ID] 所以像echo $ array [user_login],其中[ID]是$ variable [ID]

我需要一个不使用echo $ array [0] [user_login]

的解决方案
Array
(
    [0] => stdClass Object
        (
            [ID] => 15
            [user_login] => Loginname
            [user_nicename] => Loginname
            [user_email] => mail@mail.com
            [user_url] => http://www.domain.com
            [user_registered] => 2014-10-26 09:39:01
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => Test Inc
            [logo] => 
        )

    [1] => stdClass Object
        (
            [ID] => 28
            [user_login] => Loginname
            [user_nicename] => Loginname
            [user_email] => mail@mail.com
            [user_url] => http://www.domain.com
            [user_registered] => 2014-10-26 09:39:01
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => Test Inc
            [logo] => 
        )

    [2] => stdClass Object
        (
            [ID] => 13
            [user_login] => Loginname
            [user_nicename] => Loginname
            [user_email] => mail@mail.com
            [user_url] => http://www.domain.com
            [user_registered] => 2014-10-26 09:39:01
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => Test Inc
            [logo] => 
        )

    [3] => stdClass Object
        (
            [ID] => 11
            [user_login] => Loginname
            [user_nicename] => Loginname
            [user_email] => mail@mail.com
            [user_url] => http://www.domain.com
            [user_registered] => 2014-10-26 09:39:01
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => Test Inc
            [logo] => 
        )
)

3 个答案:

答案 0 :(得分:2)

您可以遍历该数组以创建一个新数组:

$newArray = array();
foreach($array as $item){
    $newArray[$item->ID] = $item;
}

然后,您可以使用$newArray[$id]->whateveritem;

访问内容

答案 1 :(得分:2)

这是一个对象数组,与数组(或多维数组)数组略有不同。

您可以遍历数组,直到找到正确的ID,然后抓住user_login。这样的东西

$myID = 15; //Id to search for

foreach ($array as $obj) {
    if($obj->ID === $myID) {
        echo $obj->user_login; //Or do something with it
    }
}

答案 2 :(得分:0)

对象数组中的项目被引用为$object->member。搜索此数组的简单方法是使用简单的foreach()循环。例如,要查找ID为28的用户,您可以执行以下操作:

foreach($array as $item) {
    if ($item->ID == '28') {
        echo 'Login is: ' . $item->user_login;
        break;
    }
}

编辑:糟糕,Trivie打败了我