简体   繁体   中英

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 . I tried it with array_chunks and array_map but can't get the expected.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM