另一种方式,而不是使用任何循环功能构建一个多维数组
问题描述:
这里是我的代码:另一种方式,而不是使用任何循环功能构建一个多维数组
$matches = Array(80246, 81227, 18848, 15444, 88114, 11488);
$info = Array("id" => "3", "url" => "http://example.com/");
function get_matches($matches, $info)
{
foreach ($matches as $match)
{
$row['target'] = $match;
$row['id'] = $info['id'];
$scr_matches[] = $row;
}
return $scr_matches;
}
$scr_matches = get_matches($matches, $info);
print_r($scr_matches);
输出:
Array
(
[0] => Array
(
[target] => 80246
[id] => 3
)
[1] => Array
(
[target] => 81227
[id] => 3
)
[2] => Array
(
[target] => 18848
[id] => 3
)
[3] => Array
(
[target] => 15444
[id] => 3
)
[4] => Array
(
[target] => 88114
[id] => 3
)
[5] => Array
(
[target] => 11488
[id] => 3
)
)
我在寻找其他的解决方案,而不是使用任何循环函数(foreach在我的情况),并给我相同的输出,我也试图使用array_map()
,但我无法让它工作,并给我输出,我期望,任何想法请吗?
答
我完全不明白你为什么要避免foreach
,因为它是写代码的simpliest和最可读的方法。但是,例如,您可以:
$matches = Array(80246, 81227, 18848, 15444, 88114, 11488);
$info = Array("id" => "3", "url" => "http://example.com/");
$iid = $info['id'];
$scr_matches = array_reduce($matches, function($t, $v) use ($iid) {
$t[] = [
'target' => $v,
'id' => $iid,
];
return $t;
}, []);
随着array_map
:
$matches = Array(80246, 81227, 18848, 15444, 88114, 11488);
$info = Array("id" => "3", "url" => "http://example.com/");
$iid = $info['id'];
$scr_matches = array_map(function($v) use ($iid) {
return [
'target' => $v,
'id' => $iid,
];
}, $matches);
这些和任何其他的解决方案仍将使用遍历数组,虽然这个过程会在引擎盖下隐藏。
非常感谢:) – user2203703