【问题标题】:php array map on nested嵌套的php数组映射
【发布时间】:2013-08-08 14:29:34
【问题描述】:

情况

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

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 循环。

【问题讨论】:

  • 修改查询以返回您想要的内容不是更容易吗?
  • @vascowhite 我可以让数据库调用挑出我想要的数据,但是我不会在第一个返回的结果集中获得最完整的流派记录。最终目标是拥有更短、更“简单”更高效的运行时代码。

标签: php arrays flatten array-map


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-05-27
    • 2013-07-17
    • 2020-09-25
    • 2021-02-08
    • 2012-12-14
    相关资源
    最近更新 更多