我有一个尴尬的需求,但我需要在将结果内爆之前将一个数组与另一个数组交错。我想我更好的选择是少说话多举例
数组一
[0] => "John has a ", [1] => "and a", [2] => "!"
数组二
[0] => 'Slingshot", [1] => "Potato"
我需要生产
John has a Slingshot and a Potato!
我的问题是我可以通过内爆来做到这一点还是我必须建立自己的功能?
简单的解决方案
$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 !
演示
可能值得看一下关于将多个数组交错成单个数组的最佳答案,这似乎是一个稍微更通用的(对于 n 个数组,而不是 2 个)版本,而不是你所追求的 :-)
$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() 检查。
改编自上面的评论。
你确定你不只是想要字符串格式吗?
echo vsprintf("John has a %s and a %s!", array('slingshot', 'potato'));
输出:
John has a slingshot and a potato!