开发者

How to convert a multidimensional array to a single dimensional array?

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?


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜