我无法弄清楚如何像这样转换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;
}
答案 0 :(得分:0)
$test = array(
"country" =>array(
"id"=> array ( 49699=> array ( 3=> 3 ) ),
"name"=> array( 0=> array ( 253=> Italy ) )
)
); // input array
$country = $test['country']; // pull countries
$new = array(); // building array
foreach($country as $key => $array) { // first array with keys "name", "id"
$i = array(); // create temp array to store values
$i['name'] = $key;
foreach($array as $key2 => $array2) { // second array with keys 49699, 0
$i['flags'] = $key2;
foreach($array2 as $key3 => $value) { // last array with keys 3, 253
$i['type'] = $key3;
$i['value'] = $value;
}
}
$new['country'][] = $i; // add new deminsion to building array
}
print_r($new);
结果将是:
Array (
[country] => Array (
[0] => Array ( [name] => id [flags] => 49699 [type] => 3 [value] => 3 )
[1] => Array ( [name] => name [flags] => 0 [type] => 253 [value] => Italy )
) )