PHP删除嵌套数组

时间:2012-09-19 11:56:14

标签: php arrays

我有一个如下所示的数组$templates

        Array
(
    [0] => Array
        (
            [displayName] => First Template
            [fileName] => path_to_first_template
        )

    [1] => Array
        (
            [displayName] => Second Template
            [fileName] => path_to_second_template
        )

    [2] => Array
        (
            [displayName] => Third template
            [fileName] => path_to_third_template
        )

)

我想让它看起来像这样:

        Array
(
    [path_to_first_template] => First Template
    [path_to_second_template] => Second Template
    [path_to_third_template] => Third Template
)

也就是说,我希望嵌套数组的fileName为新数组的键,displayName为其值。

有一种很好的方法可以做到这一点而无需循环遍历数组。我没有运气搜索,因为我不确切知道要搜索什么。

3 个答案:

答案 0 :(得分:3)

这是一个经典的foreach

$result = array();
foreach($array as $row) {
    $result[$row['fileName']] = $row['displayName'];
};

这是一种“聪明”的方法:

$result = array();
array_walk($array, function($row) use (&$result) {
    $result[$row['fileName']] = $row['displayName'];
});

正如您所看到的,第二种方法并不比第一种方法更好。唯一的好处是理论上你可以在第二个表单上堆积,因为它是一个单独的表达式,但实际上它已经是一个足够长的表达式,所以你不想这样做。

答案 1 :(得分:2)

在数组中循环并创建一个新的:

$newArray = array();
foreach($array as $val){
    $newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);

答案 2 :(得分:0)

$ret = array()
foreach ($templates as $template) {
    $ret[$template["fileName"]] = $template["displayName"];
}