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

时间:2015-10-30 22:10:49

标签: php arrays

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

1 个答案:

答案 0 :(得分:1)

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