如何删除父数组,只保留孩子?

时间:2013-06-24 22:51:33

标签: php arrays sorting

这是数组:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => John Snow
                    [id] => 2
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [name] => Arya Stark
                    [id] => 3
                )
        )

    [2] => Array
        (
            [0] => Array
                (
                    [name] => Tyrion Lannister 
                    [id] => 7
                )
        )
)

如何将上述数组转换为:

Array
(
    [2] => John Snow
    [3] => Arya Stark
    [7] => Tyrion Lannister
)

当然这只是一个小样本。我可以用3个foreach循环完成这个,但这似乎是不必要的,是否有一个PHP函数可以帮助这个?

1 个答案:

答案 0 :(得分:5)

$arr = [...];
$ans = [];
foreach($arr as $r){
    $ans[$r[0]['id']] = $r[0]['name'];
}
print_r($ans);