Skip to content

Instantly share code, notes, and snippets.

@Twipped
Created July 25, 2012 06:13
Show Gist options
  • Save Twipped/3174692 to your computer and use it in GitHub Desktop.
Save Twipped/3174692 to your computer and use it in GitHub Desktop.
array_cross
<?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);
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