Skip to content

Instantly share code, notes, and snippets.

@Problematic
Created May 24, 2011 23:44
Show Gist options
  • Save Problematic/990005 to your computer and use it in GitHub Desktop.
Save Problematic/990005 to your computer and use it in GitHub Desktop.
Function to zipper two arrays together. Preserves keys, appending unique value if duplicated.
<?php
/**
* zippers two arrays together, alternating values from each array
*
* @param array $array1
* @param array $array2
* @return array
*/
function zipperArrays(array $array1, array $array2) {
$zippered = array();
/*
* recursive function returning a key value unique across all arrays involved.
* appends number-based identifier (_1, _2, etc) to array key if it already exists.
* does not overwrite underscore values that already exist in the arrays to be zippered
*/
$getUniqueKey = function($needle, $level = 0) use(&$getUniqueKey, &$zippered, $array1, $array2) {
$uniqueNeedle = $level ? $needle.'_'.$level : $needle;
$append = '_' . $level;
if (array_key_exists($uniqueNeedle, $zippered)
|| (substr_compare($uniqueNeedle, $append, -strlen($append), strlen($append)) === 0
&& (array_key_exists($uniqueNeedle, $array1) || array_key_exists($uniqueNeedle, $array2)))) {
return $getUniqueKey($needle, ++$level);
}
return $uniqueNeedle;
};
/*
* takes an array from each() and adds the value (and key, if a string-based key is given) to $zippered.
* does not preserve numeric indexes
*/
$addValue = function(array $item) use(&$getUniqueKey, &$zippered) {
if (is_numeric($item['key'])) {
$zippered[] = $item['value'];
} else {
$zippered[$getUniqueKey($item['key'])] = $item['value'];
}
};
while ($item = each($array1)) {
$addValue($item);
$item2 = each($array2);
if ($item2) {
$addValue($item2);
}
}
// ensures that if $array2 is longer than $array1, the remainder of its values will be added to $zippered
while ($item = each($array2)) {
$addValue($item);
}
return $zippered;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment