开发者

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

开发者 https://www.devze.com 2023-03-05 04:38 出处:网络
I want to turn (in PHP) something like ([\"a\"] => ( [\"x\"] => \"foo\", [\"y\"] => \"bar\"), [\"b\"] => \"moo\",

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

精彩评论

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