note 11376 added to Array Funktionen
| From: | sorry at dont-have dot one | Date: | Sun, 18 Feb 2001 20:39:39 +0000 |
| Subject: | note 11376 added to Array Funktionen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-11222@lists.php.net to get a copy of this message | ||
I was looking for a function to merge a multidimensional array into one dimension, but I didn't
found any.
This is my soluten for this problem:
function array_flatten($array, $string = '_') {
if(is_array($array)) {
while(list($key,$val) = each($array)) {
if(is_array($val)) {
// If there are more dimensions, we have
// to call this function recursivly.
$tmparr = array_flatten($val, $string);
while(list($key1,$val1) = each($tmparr)) {
$tmp = $key.$string.$key1;
$return[$tmp] = $val1;
}
} else {
$return[$key] = $val;
}
}
} else {
echo '<b>Warning</b>: Variable passed to array_flatten() in
<b>'.__FILE__.'</b> is not an array';
$return = false;
}
// This will be an 1-dimensional array or false
return $return;
}
Example:
$foobar[1][blah][hello] = 'test1';
$foobar[1][blub][nice] = 'test2';
$example = array_flatten($foobar);
$example will be the following array:
$foobar[1_blah_hello] = 'test1';
$foobar[1_blub_nice] = 'test2';
You could replace the '_' by any other string if you user this string as a second
parameter for array_flatten().
For examplte, array_flatten($array,'.') will use the '.' instead of the
'_'.
http://www.php.net/manual/de/ref.array.php