Created
July 25, 2012 06:13
-
-
Save Twipped/3174692 to your computer and use it in GitHub Desktop.
array_cross
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
<?php | |
function array_cross() { | |
$arrays = func_get_args(); | |
//force indexed arrays, stripping any extra keys. | |
array_walk($arrays, function (&$n) { | |
return is_array($n) ? array_values($n) : null; | |
}); | |
//make sure we're only dealing with arrays | |
$arrays = array_filter($arrays); | |
$arrays = array_values($arrays); | |
//if there aren't at least two valid inputs, there is nothing more to be done. | |
if (count($arrays) < 2) return $arrays; | |
//collect the sizes of the arrays | |
$counts = array_map(function ($n) { | |
return count($n); | |
}, $arrays); | |
$maxLength = max($counts); | |
$vertex = count($arrays); | |
$results = array_fill(0, $vertex, array()); | |
for ($i=0;$i<$maxLength;$i++) { | |
for ($j=0;$j<$vertex;$j++) { | |
$results[$i][$j] = isset($arrays[$j][$i]) ? $arrays[$j][$i] : null; | |
} | |
} | |
return $results; | |
} | |
$a = Array('a', 'b', 'c', 'd'); | |
$b = Array('e', 'f', 'g', 'h', 'z', 'x'); | |
$c = Array('i', 'j', null,'k', 'l'); | |
$d = array_cross($a, $b, $c); | |
print_r($d); |
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
Array | |
( | |
[0] => Array | |
( | |
[0] => a | |
[1] => e | |
[2] => i | |
) | |
[1] => Array | |
( | |
[0] => b | |
[1] => f | |
[2] => j | |
) | |
[2] => Array | |
( | |
[0] => c | |
[1] => g | |
[2] => | |
) | |
[3] => Array | |
( | |
[0] => d | |
[1] => h | |
[2] => k | |
) | |
[4] => Array | |
( | |
[0] => | |
[1] => z | |
[2] => l | |
) | |
[5] => Array | |
( | |
[0] => | |
[1] => x | |
[2] => | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment