我不知道如何像这样转换 n 数组
Array (
[Country] => Array (
[id] => Array ( [49699] => Array ( [3] => 3 ) )
[name] => Array ( [0] => Array ( [253] => Italy ) )
)
)
其中键的数量和只有一个值,类似这样的东西
Array (
[Country] => Array (
[0] => Array( [name] => id, [flags] => 49699, [type] => 3, [value] => 3),
[1] => Array( [name] => name, [flags] => 0, [type] => 253, [value] => Italy),
)
)
我曾尝试编写一个递归函数,但一开始就深深陷入困境。
function getPost($post) {
function _traverse($elem, $cnt, $res) {
// known structure of keys - value
$names = Array('name', 'flags', 'type', 'value');
if(!is_array($elem)) {
$res[$names[$cnt]] = $elem;
$cnt = 0;
} else {
$k = key($elem);
$v = $elem[$k];
$res[$names[$cnt]] = $k;
_traverse($v, ++$cnt, $res);
return $res;
}
echo '<br/>';
print_r($res); // last copy of function give what i want
}
$res = Array(); // new array to save result
$table = key($post); // 1st key
$arr = $post[$table]; // 1st element
$res = _traverse($arr, 0, $res);
echo '<br/><br/><br/>';
print_r($res); // give res from first copy
}
不幸的是,经过几个小时的头痛,我没有想出更好的办法。有人可以救我吗,拜托。提前致谢!
更新。所以我最终来到了这里
function getPost($post) {
function _traverse($elem, $cnt, $res) {
$names = Array('name', 'flags', 'type', 'value');
if(is_array($elem)) {
$k = key($elem);
$v = $elem[$k];
$res[$names[$cnt]] = $k;
$res = _traverse($v, ++$cnt, $res);
} else {
$res[$names[$cnt]] = $elem;
}
return $res;
}
$fields = Array();
$table = key($post);
$arr = $post[$table];
foreach($arr as $key => $val) {
$fields[] = _traverse(Array($key => $val), 0, Array());
}
return $fields;
}