2

Possible Duplicate:
Convert multidimensional array into single array

I have this array:

Array
(
    [one] => one_value
    [two] => Array
        (
            [four] => four_value
            [five] => five_value
        )

    [three] => Array
        (
            [six] => Array
                (
                    [seven] => seven_value
                )

        )

)

And I want to convert it to this type of array:

Array
(
    [one] => one_value
    [two-four] => four_value
    [two-five] => five_value
    [three-six-seven] => seven_value
)

How can I achieve this? With some kind of "recursiveness"? But how? :\ Thanks in advance!

Community
  • 1
  • 1
MGP
  • 653
  • 1
  • 14
  • 33
  • @Yoel It is if you want to save an array with its structure in a database type "key" => "value" so you can rebuild it in a simple manner.. at least this is the best ideia i got so far.. probably not the best? – MGP Feb 23 '12 at 16:18
  • For merging the keys, see [Get array's key recursively and create underscore seperated string](http://stackoverflow.com/q/2749398/367456) – hakre Feb 23 '12 at 16:19

2 Answers2

3
<?php
$array = array(
    'one' => 'one_value',
    'two' => array
        (
            'four' => 'four_value',
            'five' => 'five_value'
        ),

    'three' => array
        (
            'six' => array
                (
                    'seven' => 'seven_value'
                )

        )
);

function flatten($array, $prefix = '') {
    $arr = array();
    foreach($array as $k => $v) {
        if(is_array($v)) {
            $arr = array_merge($arr, flatten($v, $prefix . $k . '-'));
        }
        else{
            $arr[$prefix . $k] = $v;
        }
    }
    return $arr;
}

var_dump(flatten($array));

//output:
//array(4) {
//  ["one"]=>
//  string(9) "one_value"
//  ["two-four"]=>
//  string(10) "four_value"
//  ["two-five"]=>
//  string(10) "five_value"
//  ["three-six-seven"]=>
//  string(11) "seven_value"
//}

Running example

jprofitt
  • 10,874
  • 4
  • 36
  • 46
1

You can implement recursive processing with a stack:

$separator = '-';
$flat = array();

while ($array);
{
    $key   = key($array);
    $value = array_shift($array);

    if (is_array($value))
    {
        foreach($value as $subKey => $node)
        {
            $array[$key.$separator.$subKey] = $node;
        }
    }
    else
    {
        $flat[$key] = $value;
    }
}

Output (Demo):

Array
(
    [one] => one_value
    [two-four] => four_value
    [two-five] => five_value
    [three-six-seven] => seven_value
)
hakre
  • 193,403
  • 52
  • 435
  • 836