隔离包含索引数据行的数组列,然后展开/合并以形成行数组


Isolate an array column containing indexed rows of data, then flatten/merge to form an array of rows

情况

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

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'
            ),
        )
    )
)

情况

我想要的是一个数组,它只包含模块,如下所示:

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']
}

我希望能够切出前臂环,如上所示。

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
    )
);