Created
January 21, 2014 09:46
-
-
Save nabil-boag/8537228 to your computer and use it in GitHub Desktop.
PHP Function for array zip merge. Merges two arrays like a zipping. Uneven sized arrays get items appended to the end.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Merges two arrays like a zipping. Uneven sized arrays get items | |
* appended to the end. | |
* | |
* @param array $a An array to merge | |
* @param array $b Another array to merge | |
* @return array An array of merged values | |
*/ | |
function array_zip_merge(array $a, array $b) { | |
$return = array(); | |
$count_a = count($a); | |
$count_b = count($b); | |
if ($count_b < $count_a) { | |
// Ensure $b is greater or equal to $a | |
$temp = $a; | |
$b = $a; | |
$a = $temp; | |
} | |
// Zip arrays | |
for ($i = 0; $i < $count_a; $i++) { | |
$return = array_merge_recursive($return, array_slice($a, $i, 1, true)); | |
$return = array_merge_recursive($return, array_slice($b, $i, 1, true)); | |
} | |
$difference = $count_b - $count_a; | |
if ($difference) { | |
// There are more items to add on end so pop them at the end | |
$return = array_merge_recursive($return, | |
array_slice($b, $count_a, $difference, true)); | |
} | |
return $return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The swap function is wrong, it just duplicates the a and doesn't update the counts.
This is a correct implementation