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?

Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102

2 Answers2

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);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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

PJP
  • 756
  • 3
  • 15