1

I want to turn (in PHP) something like

(["a"] => (
    ["x"] => "foo",
    ["y"] => "bar"),
["b"] => "moo",
["c"] => (
    ["w"] => (
        ["z"] => "cow" )
        )
)

into

(["a.x"] => "foo",
["a.y"] => "bar",
["b"] => "moo",
["c.w.z"] => "cow")

How do I achieve that?

2
  • is it only 3 levels deep or arbitrary levels deep? Commented May 12, 2011 at 14:05
  • It's arbitrary levels deep, although it rarely goes deeper than 4 levels. Commented May 12, 2011 at 14:07

2 Answers 2

7

You could create a recursive function:

function flatten($arr, &$out, $prefix='') {
    $prefix = $prefix ? $prefix . '.' : '';
    foreach($arr as $k => $value) {
        $key =  $prefix . $k;
        if(is_array($value)) {
            flatten($value, $out, $key);
        }
        else {
            $out[$key] = $value;
        }
    }
}

You can use it as

$out = array();
flatten($array, $out);
Sign up to request clarification or add additional context in comments.

3 Comments

How do I store the full array path as an objects identifier with this one?
@Cobra: I don't know what you mean. Please elaborate.
$key = $prefix ? $prefix . '.' . $k : $k; It actually already store the full array path with this line. +1 for this solution.
1

You've got something nice here: http://davidwalsh.name/flatten-nested-arrays-php

1 Comment

On the right track but that by itself won't make keys like OP wants

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.