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
精彩评论