从对象数组

时间:2016-10-20 23:33:51

标签: php arrays object

我有一个对象,包含一个对象数组,其中包含一组值:

stdClass Object (
    [devices] => Array (
    [0] => stdClass Object ( 
        [location] => 1
        [delegate] => 
        [type] => 1 
        [id] => 1234 
        [IP] => 1.2.3.4
        [name] => host1
        [owner] => user6 
        [security] => 15
        )
    [1] => stdClass Object (
        [location] => 2
        [delegate] => 
        [type] => 1 
        [id] => 4321 
        [IP] => 4.3.2.1
        [name] => host2
        [owner] => user9 
        [security] => 15
        )
    )
)

我想以下列形式将id和名称提取到数组中: $ devices [' id'] = $ name;

我考虑使用array_map()功能,但无法解决如何使用它......有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这将为您生成一个新的数组,就像我想要的那样

我知道你说delegate是一个对象,但打印不会那样显示

$new = array();
foreach($obj->devices as $device) {
    $new[][$device->id] = $device->name;
}

答案 1 :(得分:0)

这样的事情不起作用吗?未经测试但它循环通过对象结构来提取我认为你需要的东西。

$devices = myfunction($my_object);

function myfunction($ob){
    $devices = array();
    if(isset($ob->devices)){
        foreach($ob->devices as $d){
            if(isset($d->delegate->name && isset($d->delegate->id))){
                $devices[$d->delegate->id] = $d->delegate->name;
            }
        }
    }
    return($devices);
}

答案 2 :(得分:0)

我通常使用此函数生成所有子数组和父数组stdclass / object,但仍然使密钥相同:

function GenNewArr($arr=array()){
    $newarr = array();
    foreach($arr as $a=>$b){
        $newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
    }
    return $newarr;
}