我無法弄清楚如何正數組轉換這樣返回值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
}
不幸的是,經過幾個小時的頭痛,我沒有想出更好的東西。請有人救我吧。提前致謝!
UPDATE。所以,我在這裏結束了
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;
}
看來我需要$水庫= _traverse($ V,+ $ CNT,$水庫);而不是_traverse($ v,++ $ cnt,$ res);返回$ res; – kostya