Voting

: max(three, two)?
(Example: nine)

The Note You're Voting On

g.REMOVETHIS.vincendon AT vithemis.com
12 years ago
I was looking for a function that could combine an array to multiple one, for my MySQL GROUP_CONCAT() query, so I made this function.

<?php
function array_combine_array(array $keys)
{
$arrays = func_get_args();
$keys = array_shift($arrays);

/* Checking if arrays are on the same model (array('INDEX'=> array()) or array()) */
$check = count(array_unique(array_map('is_array',array_map('current',$arrays)))) === 1;
if (!
$check) { trigger_error('Function array_combine_array() expects all parameters to be same type array or array of array',E_USER_NOTICE); return array(); }

/* Checking the model of arrays, array('INDEX' => array()) or Array() */
$assocArray = is_array(array_shift(array_map('current',$arrays)));

/* If empty $Keys is given, we fill an empty array */
if (empty($keys)) $keys = array_keys(array_fill(0,max(($assocArray) ? array_map('count',array_map('current',$arrays)) : array_map('count',$arrays)),'foo'));

/* Init */
$ret=array();$i=0;
/* Cycling on each keys values, making an offset for each */
foreach($keys as $v)
{
/* Cycling on arrays */
foreach ($arrays as $k)
{
if (
$assocArray)
{
/* Getting the index of the element */
$key = key($k);
/* If the offset exists, we place it */
$ret[$v][$key] = isset($k[$key][$i]) ? $k[$key][$i]:false;
}
/* Making the array with auto-made index */
else
$ret[$v][] = isset($k[$i]) ? $k[$i]: false;
}
/* Getting the next offset */
$i++;
}
return
$ret;
}

/* Examples */
$r = array(1,2,4,10);

$a1 = array('one','two','four','ten');
$a2 = array('un','deux','quatre','dix');
$a3 = array('uno','dos','quatro','diez');

print_r(array_combine_array($r,array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Associative index, associative subarray indexes */
print_r(array_combine_array($r,$a1,array('french' => $a2),array('spanish' => $a3))); /* Ouputs Error */
print_r(array_combine_array($r,$a1,$a2,$a3)); /* Associative index, auto-made subarray indexes */
print_r(array_combine_array(array(),array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Auto-made index, associative subarray indexes */
?>

<< Back to user notes page

To Top