2013-07-31 144 views
1

我無法弄清楚如何正數組轉換這樣返回值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; 
} 
+0

看來我需要$水庫= _traverse($ V,+ $ CNT,$水庫);而不是_traverse($ v,++ $ cnt,$ res);返回$ res; – kostya

回答

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) 
)) 
+0

感謝您的回覆,但如果密鑰的數量會發生變化,那該怎麼辦?我只想要一個函數將名稱從已知的數組結構映射到$ _POST n-array中的已編譯的表單數據。 – kostya

+0

鍵的數量變化如何?舉個例子 ? –