我有一个尴尬的需求,但我需要在插入结果之前将数组与另一个数组交错。我想我更好的选择是更少说话更多的例子
第一个数组
[0] => "John has a ", [1] => "and a", [2] => "!"
第二个数组
[0] => 'Slingshot", [1] => "Potato"
我需要制作
John has a Slingshot and a Potato!
我的问题是我可以用内爆来做到这一点,还是我必须建立自己的功能?
答案 0 :(得分:3)
简单解决方案
$a = [0 => "John has a", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];
vsprintf(implode(" %s ", $a),$b);
在array_map
implode
$a = [0 => "John has a", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];
$data = [];
foreach(array_map(null, $a, $b) as $part) {
$data = array_merge($data, $part);
}
echo implode(" ", $data);
另一个例子:
$data = array_reduce(array_map(null, $a, $b), function($a,$b){
return array_merge($a, $b);
},array());
echo implode(" ", $data);
两者都会输出
John has a Slingshot and a Potato !
演示
答案 1 :(得分:1)
可能值得查看Interleaving multiple arrays into a single array上的最佳答案,这似乎是一个稍微更一般的(对于n数组,而不是2)版本的其他正是你所追求的: - )
答案 2 :(得分:1)
$a = [0 => "John has a ", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];
foreach($a AS $k=>$v){
echo trim($v).' '.trim($b[$k]).' ';
}
如果您修复空间以使它们保持一致:)
您也可能想要添加一个isset()检查。
答案 3 :(得分:1)
改编自comment以上。
您确定不只是想要字符串格式吗?
echo vsprintf("John has a %s and a %s!", array('slingshot', 'potato'));
输出:
John has a slingshot and a potato!