这是我的代码:
$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()
但我无法得到它工作,并给我我期望的输出,任何想法好吗?
答案 0 :(得分:2)
我绝对不明白为什么你要避免使用foreach
,因为它是用于编写代码的最简单和最可读方法。但是例如你可以:
$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);
这些和任何其他解决方案仍将使用循环数组,但此过程将隐藏在引擎盖下。