note 60518 deleted from ref.array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: spam at madhermit dot net 

----

Here is a function that recursively flattens an multidimensional array while maintaining keys. Hopefully it is useful to someone..

Example Input:

Array
(
    [name] => John Doe
    [email] => [email protected]
    [addresses] => Array
        (
            [1] => Array
                (
                    [address] => 555 Somewhere
                    [city] => Podunk
                    [state] => CA
                    [zip] => 90120
                )

            [2] => Array
                (
                    [address] => 333 Someother Place
                    [city] => Podunk
                    [state] => CA
                    [zip] => 91103
                )

        )

)
Example output:
Array
(
    [name] => John Doe
    [email] => [email protected]
    [address1] => 555 Somewhere
    [city1] => Podunk
    [state1] => CA
    [zip1] => 90120
    [address2] => 333 Someother Place
    [city2] => Podunk
    [state2] => CA
    [zip2] => 91103
)

<?
function flattenArray($array,$keyname='')
{
    $tmp = array();
    foreach($array as $key => $value)
    {
        if(is_array($value))
            $tmp = array_merge($tmp,flattenArray($value,$key));
        else
            $tmp[$key.$keyname] = $value;
    }
    return $tmp;
}
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.