note 69235 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:04:35 +0000 |
| Subject: | note 69235 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199453@lists.php.net to get a copy of this message | ||
Note Submitter: ob at babcom dot biz
----
Regarding the function of spam at madhermit dot net from January 9th 2006:
That function only preserves the deepest keys and values.
If you try to flatten an array with that function where the deepest instance of keys might be the
same where as keys in the "key-path" are different, values will be overwritten.
So here is a function that preserves the whole key-path and the keys of the flattened array will be
string keys consisting of the key-path separated by $Separator.
<?php
// flatten multidimensional array to one dimension
// preserves keys by generating a key for the flattened array which consists of the
// key-path of the multidimensional array separated by $Separator
// usage: array ArrayFlatten( array Array [, string Separator] )
function ArrayFlatten($Array,$Separator="_",$FlattenedKey='') {
$FlattenedArray=Array();
foreach($Array as $Key => $Value) {
if(is_Array($Value))
$FlattenedArray=Array_merge($FlattenedArray,
ArrayFlatten($Value,$Separator,
(strlen($FlattenedKey)>0
?$FlattenedKey.$Separator
:"").$Key)
);
else
$FlattenedArray[$FlattenedKey.$Separator.$Key]=$Value;
}
return $FlattenedArray;
}
?>