What is the fastest or most convenient possible way to convert a multi-dimensional array to a single HTML-like array (the method that is used to set the name
attribute in HTML forms)? For example,
$ar = [
'x' => ['a' => 1, 'b' => 2, 'c' => 3],
'y' => ['yy' => ['yyy' => 3]],
'z' => 3333,
'm' => [1, 2],
];
should be converted to:
$ar = [
'x[a]' => 1,
'x[b]' => 2,
'x[c]' => 3,
'y[yy][yyy]' => 3,
'z' => 3333,
'm[0]' => 1,
'm[1]' => 2,
];
Here is my first try:
$ar = [
'x' => ['a' => 1, 'b' => 2, 'c' => 3],
'y' => ['yy' => ['yyy' => '3']],
'z' => 3333,
'm' => [1, 'x']
];
function convert($key, $value, &$new)
{
foreach ($value as $k => $v) {
if (is_array($v)) {
convert($key."[$k]", $v, $new);
}
else {
$new[$key."[$k]"] = $v;
}
}
}
$r = [];
convert(null, $ar, $r);
print_r($r);;
答案 0 :(得分:1)