嵌套结构上的php数组映射 情况
我有一个从数据库调用返回的数组结果。在下面的示例中,它获取了许多类型的书籍。使用联接,查询同时从每个流派中提取书籍。以下是一个假设结果集:嵌套结构上的php数组映射 情况,php,arrays,flatten,array-map,Php,Arrays,Flatten,Array Map,我有一个从数据库调用返回的数组结果。在下面的示例中,它获取了许多类型的书籍。使用联接,查询同时从每个流派中提取书籍。以下是一个假设结果集: array( [0] => array ( 'id' => 1, 'title' => 'ficton' 'modules' => array( [0] => array( 'other_id' => 1
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']
}
我希望能够切断foreach循环,如上图所示。PHP5.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
)
);
修改查询以返回所需内容不是更容易吗?@vascowhite我可以让DB调用挑出我想要的数据,但这样,我就无法在第一个返回的结果集中获得最完整的类型记录。最终目标是拥有更短、更“简单”和更高效的运行时代码。