php - Converting multi-dimensional array to a single HTML-like array? -
what fastest or convenient possible way convert multi-dimensional array single html-like array (the method used set name
attribute in html forms)? example,
$ar = [ 'x' => ['a' => 1, 'b' => 2, 'c' => 3], 'y' => ['yy' => ['yyy' => 3]], 'z' => 3333, 'm' => [1, 2], ];
should 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 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 $k => $v) { if (is_array($v)) { convert($key."[$k]", $v, $new); } else { $new[$key."[$k]"] = $v; } } } $r = []; convert(null, $ar, $r); print_r($r);;
i not know speed, convenient way trick:
$ar = convert_array( $ar ); function convert_array( $a, $key = '' ) { static $arr = array(); foreach( $a $k => $v ) { $key_name = $key == '' ? $k : $key . '[' . $k . ']'; if ( is_array( $v) ) { convert_array( $v, $key_name ); } else { $arr[$key_name] = $v; } } return $arr; }
Comments
Post a Comment