嵌套的php数组映射

时间:2013-08-07 09:23:25

标签: php arrays flatten array-map

情况

我有从数据库调用返回的数组结果。在下面的示例中,它提取许多类型,这些类型可以包含多个书籍。使用联接,查询同时从每个类型中提取书籍。这是一个假设的结果集:

array(
    [0] => array (
        'id' => 1,
        'title' => 'ficton'
        'modules' => array(
            [0] => array(
                'other_id' => 1
                'other_title' => 'James Clavell'
            ),
            [1] => array(
                'other_id' => 2
                'other_title' => 'Terry Pratchett'
            ),
            [2] => array(
                'other_id' => 3
                'other_title' => 'Robert Ludlum'
            ),
        ),
    [1] => array (
        'id' => 2,
        'title' => 'non-ficton'
        'modules' => array(
            [1] => array(
                'other_id' => 5
                'other_title' => 'An excessive book of excessively interesting things'
            ),
            [2] => array(
                'other_id' => 6
                'other_title' => 'It\'s late, I can\'t think of what to put here'
            ),
        )
    )
)

情况

我最终想要的是一个只包含 modules 的数组,如下所示:

array(
    [0] => array(
        'other_id' => 1
        'other_title' => 'James Clavell'
    ),
    [1] => array(
        'other_id' => 2
        'other_title' => 'Terry Pratchett'
    ),
    [2] => array(
        'other_id' => 3
        'other_title' => 'Robert Ludlum'
    ),
    [3] => array(
        'other_id' => 5
        'other_title' => 'An excessive book of excessively interesting things'
    ),
    [4] => array(
        'other_id' => 6
        'other_title' => 'It\'s late, I can\'t think of what to put here'
    )
)

问题

现在,我通过迭代实现这一点没有问题但是,感觉有更好的(未发现的)意味着实现这一点。

问题

是创建所需结果的快捷方式。我到目前为止的代码列在下面,并不是一个难以解决的问题。我更好奇的是,是否有更好的版本执行以下操作。

丑陋的代码

以下是100%工作的代码版本,但其迭代次数比我可以考虑的要多。

$aryTemp = array();
foreach($aryGenres as $intKey => $aryGenre) {
    foreach($aryGenre['modules'] as $aryModule) {
        $aryTemp[] = $aryModule
    }
}

尝试使用数组映射

尝试使用数组映射并且可怕地失败

$aryTemp = array();
foreach($aryGenres as $intKey => $aryGenre) {
    $aryTemp[] = array_map(
        function($aryRun) { return $aryRun;
    },$aryGenre['modules']

}

我希望能够切出foreach循环,如上所示。

1 个答案:

答案 0 :(得分:2)

PHP 5.6 +:

$modules = array_merge(...array_column($arr, 'modules'));

# Allowing empty array
$modules = array_merge([], ...array_column($arr, 'modules'));

PHP 5.5:

$modules = call_user_func_array('array_merge', array_column($arr, 'modules'));

PHP~5.4:

$modules = call_user_func_array(
    'array_merge',
    array_map(
        function ($i) {
            return $i['modules'];
        },
        $arr
    )
);