如何将多维数组转换为单维数组?

Cob*_*ast 1 php arrays multidimensional-array

我想转(在PHP中)类似的东西

(["a"] => (
    ["x"] => "foo",
    ["y"] => "bar"),
["b"] => "moo",
["c"] => (
    ["w"] => (
        ["z"] => "cow" )
        )
)
Run Code Online (Sandbox Code Playgroud)

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

我如何实现这一目标?

Fel*_*ing 7

你可以创建一个递归函数:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以用它作为

$out = array();
flatten($array, $out);
Run Code Online (Sandbox Code Playgroud)