[英]Merge two array into one into chunks
I have the following arrays 我有以下数组
$arr1 = array(
array('ctype'=>'fr', 'type'=>'fr'),
array('ctype'=>'fasdf', 'type'=>'fr'),
array('ctype'=>'fdfdf', 'type'=>'fr'),
array('ctype'=>'fhjdf', 'type'=>'fr'),
array('ctype'=>'fsf', 'type'=>'fr'),
array('ctype'=>'vndf', 'type'=>'fr'),
array('ctype'=>'fnsdf', 'type'=>'fr')
);
$arr2 = array(
array('ctype'=>'fr', 'type'=>'ln'),
array('ctype'=>'fasdf', 'type'=>'ln'),
array('ctype'=>'fayf', 'type'=>'ln'),
array('ctype'=>'fauf', 'type'=>'ln')
);
I want to merge this array into one but into chunks with difference of 2 something like 我想将此数组合并为一个数组,但合并为两个不同的块,例如
$main_arr = array(
array('ctype'=>'fr', 'type'=>'fr'),
array('ctype'=>'fasdf', 'type'=>'fr'),
array('ctype'=>'fr', 'type'=>'ln'),
array('ctype'=>'fasdf', 'type'=>'ln'),
array('ctype'=>'fdfdf', 'type'=>'fr'),
array('ctype'=>'fhjdf', 'type'=>'fr'),
array('ctype'=>'fayf', 'type'=>'ln'),
array('ctype'=>'fauf', 'type'=>'ln')
array('ctype'=>'fsf', 'type'=>'fr'),
array('ctype'=>'vndf', 'type'=>'fr'),
array('ctype'=>'fnsdf', 'type'=>'fr')
);
As you see i want to take 2 values from arr1 then 2 from arr2 and if the value not exists in like the example $arr2
then get and push the values from $arr1
. 如您所见,我想从arr1中获取2个值,然后从arr2中获取2个,如果像示例
$arr2
这样不存在该值,则从$arr1
获取并推送这些值。 I tried it with array_chunks
and array_map
but can't get the expected. 我用
array_chunks
和array_map
尝试了array_chunks
,但没有得到预期的结果。
This is what i tried: 这是我尝试的:
// Divide foursome into chunks
$fr = array_chunk($arr1, 2);
$ln = array_chunk($arr2, 2);
// Can't provide the expected result
$main = array_map(NULL, $fr, $ln);
I think you're after something like this: 我认为您正在追求这样的事情:
function combine($a1, $a2) {
if (is_array($a2) && count($a2)) {
$a1 = array_merge($a1, $a2);
}
return $a1;
}
$m = array_map('combine', $fr, $ln);
$main = array();
foreach ($m as $idx => $ars) {
$main = array_merge($main, $ars);
}
The first point to note is that the number of arrays passed to array_map() has to match the number of parameters taken by your callback function. 首先要注意的是,传递给array_map()的数组数必须与回调函数采用的参数数匹配。
The second point to note is that "chunking" adds a new level to your array, so you need some way to "flatten" the result of combining the two "chunked" arrays. 要注意的第二点是,“分块”将新级别添加到数组中,因此您需要某种方式来“展平”组合两个“分块”数组的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.