PHPst - 1 year ago 121
PHP Question

# Converting multi-dimensional array to a single HTML-like array?

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

Answer Source

I do not know about speed, but this is a convenient way to do the trick:

``````\$ar = convert_array( \$ar );

function convert_array( \$a, \$key = '' ) {
static \$arr = array();
foreach( \$a as \$k => \$v ) {
\$key_name = \$key == '' ? \$k : \$key . '[' . \$k . ']';
if ( is_array( \$v) ) {
convert_array( \$v, \$key_name );
} else {
\$arr[\$key_name] = \$v;
}
}
return \$arr;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download