0

Possible Duplicate:
PHP Walk through multidimensional array while preserving keys

I have a deep array like this one:

array {
  ["key1"] => "A"
  ["key2"] => "B"
  ["key3"] => array {
                ["subkey1"] => "C"
                ["subkey2"] => array {
                                  ["subsubkey1"] => "D"
                               }
              }

}

I don't know how deep this array will get. Now I want to convert it to an array that looks like this:

array {
   array {
  ["key1"] => "A"
  ["key2"] => "B"
  ["key3.subkey1"] => "C"
  ["key3.subkey2.subsubkey1"] = > "D"
}

How would I do that? I guess it needs a recursion?

6
  • 4
    Yes, recursion would be a good way to handle it. What have you tried and where exactly are you stuck? Commented Aug 16, 2012 at 8:19
  • Please use the search, this has been asked and answered before. You can do that with recursion or with a stack. Commented Aug 16, 2012 at 8:24
  • @hakra: the selected answer there is terribly unreadable :-S And looks like it doesn't work as expected Commented Aug 16, 2012 at 8:26
  • @hakra: I believe you could fix your answer yourself :-) As op mentioned it doesn't work on one case, and it is still buggy Commented Aug 16, 2012 at 8:30
  • @zerkms: You mean this one? Php multidimensional array to simple array - Or this one Get array's key recursively and create underscore seperated string? Commented Aug 16, 2012 at 8:35

2 Answers 2

2

As simple as

$array = array(
    'a' => array(
        'b' => array(
            'c' => 'val'
        ),
        'd' => 'val2'
    ),
    'e' => 'val3'
);

var_dump(collapse($array));

function collapse($array)
{
    $result = array();
    foreach ($array as $key => $val) {
        if (is_array($val)) {
            foreach (collapse($val) as $nested_key => $nested_val) {
                $result[$key . '.' . $nested_key] = $nested_val;
            }
        } else {
            $result[$key] = $val;
        }
    }

    return $result;
}

http://ideone.com/ieSZ6

PS: usually I don't like to give complete solutions, but in this case - the solution might be too difficult for newbie

Sign up to request clarification or add additional context in comments.

Comments

2

As written this can be done with recursion or by using a stack. This is an example of using a stack:

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

while ($array)
{
    list($key, $value) = array(key($array), array_shift($array));
    if (is_array($value))
    {
        foreach($value as $subKey => $node)
            $array[$key.$separator.$subKey] = $node;
        continue;
    }
    $flat[$key] = $value;
}

The result then is in $flat, with your $array data like so:

Array
(
    [key1] => A
    [key2] => B
    [key3.subkey1] => C
    [key3.subkey2.subsubkey1] => D
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.