PHP - 将阵列提升一级的最佳方法

时间:2015-11-04 04:08:09

标签: php

我有这个嵌套数组:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => Adam Smith
                )

            [ef] => Array
                (
                    [rate] => 0
                    [superannuation] => 9.5
                    [pportable_lsl] => 0
                    [hours_per_day] => 0
                    [hours_per_week] => 0
                    [weeks_oer_year] => 0
                )

        )
 )

我希望将所有子元素都带到顶级元素。例如:

Array
(
    [0] => Array
        (
           [name] => Adam Smith
           [rate] => 0
           [superannuation] => 9.5
           [pportable_lsl] => 0
           [hours_per_day] => 0
           [hours_per_week] => 0
           [weeks_oer_year] => 0
        )
 )

使用PHP内置函数实现此目的的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您需要简单地合并数组。

这可以通过内置函数中的PHP来完成:array_merge_recursive()

工作示例:

<?php
$ar1 = array("name" =>  'Adam Smith');
$ar2 = array('rate' => 0, 'superannuation' => 9.5, 'pportable_lsl' => 0, 'hours_per_day' => 0,
'hours_per_week' => 0, 'weeks_oer_year' =>  0);
$result = array_merge_recursive($ar1, $ar2);
echo '<pre>';
print_r($result);
echo '</pre>';
?>

Oupput:

Array
(
    [name] => Adam Smith
    [rate] => 0
    [superannuation] => 9.5
    [pportable_lsl] => 0
    [hours_per_day] => 0
    [hours_per_week] => 0
    [weeks_oer_year] => 0
)

See it live here