note 85029 modified in function.array-merge by felipe

From: Date: Tue, 12 Aug 2008 13:22:31 +0000
Subject: note 85029 modified in function.array-merge by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-143395@lists.php.net to get a copy of this message
I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays. Here's my version, You can pass any number of arrays and it will interlace and key them properly. <?php function array_interlace() { $args = func_get_args(); $total = count($args); if($total < 2) { return FALSE; } $i = 0; $j = 0; $arr = array(); foreach($args as $arg) { foreach($arg as $v) { $arr[$j] = $v; $j += $total; } $i++; $j = $i; } ksort($arr); return array_combine(range(0, (count($arr) - 1)), array_values($arr)); } ?> Example usage: <?php $a = array('a', 'b', 'c', 'd'); $b = array('e', 'f', 'g'); $c = array('h', 'i', 'j'); $d = array('k', 'l', 'm', 'n', 'o'); print_r(array_interlace($a, $b, $c, $d)); ?> result: Array ( [0] => a [1] => e [2] => h [3] => k [4] => b [5] => f [6] => i [7] => l [8] => c [9] => g [10] => j [11] => m [12] => d [13] => n [14] => o ) This function requires PHP 5's array_combine. If you're using PHP 4, you can grab an array_combine function from the notes on that function. Let me know if you improve on it. --was-- I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays. Here's my version, You can pass any number of arrays and it will interlace and key them properly. function array_interlace() { $args = func_get_args(); $total = count($args); if($total < 2) { return FALSE; } $i = 0; $j = 0; $arr = array(); foreach($args as $arg) { foreach($arg as $v) { $arr[$j] = $v; $j += $total; } $i++; $j = $i; } ksort($arr); return array_combine(range(0, (count($arr) - 1)), array_values($arr)); } Example usage: $a = array('a', 'b', 'c', 'd'); $b = array('e', 'f', 'g'); $c = array('h', 'i', 'j'); $d = array('k', 'l', 'm', 'n', 'o'); print_r(array_interlace($a, $b, $c, $d)); result: Array ( [0] => a [1] => e [2] => h [3] => k [4] => b [5] => f [6] => i [7] => l [8] => c [9] => g [10] => j [11] => m [12] => d [13] => n [14] => o ) This function requires PHP 5's array_combine. If you're using PHP 4, you can grab an array_combine function from the notes on that function. Let me know if you improve on it. http://php.net/manual/en/function.array-merge.php

« previous php.notes (#143395) next »