2014-04-30 189 views
0

我有一個帶索引子數組的關聯數組,每個數組包含包含內容和索引的關聯數組。所以像這樣(在PHP):將關聯數組轉換爲索引數組的方法

$assoc_arr = 
array("second" => array(
         array("position" => 4, 
          "content" => "Valiant"), 
         array("position" => 5, 
          "content" => "Hail") 
        ), 
     "first" => array(
         array("position" => 0, 
          "content" => "Hail"), 
         array("position" => 3, 
          "content" => "Victors"), 
         array("position" => 2, 
          "content" => "the"), 
         array("position" => 1, 
          "content" => "to") 
        ) 
); 

我希望把所有那些爲索引的數組,其中的指數是關聯數組中的「位置」。所以,最終的陣列應該是:

Array ([0] => Hail [1] => to [2] => the [3] => Victors [4] => Valiant [5] => Hail) 

目前,我合併所有的數組的最高水平數組內,然後通過各那些子陣列的位置進行排序,然後推內容創建索引數組按順序放到一個新的陣列上。如此:

$pos_arr = array_merge($assoc_arr["second"], $assoc_arr["first"]); 
usort($pos_arr, function($a, $b) { 
    return $a["position"] >= $b["position"] ? 1 : -1; 
}); 

$indexed_arr = array(); 

foreach ($pos_arr as $elem) { 
    array_push($indexed_arr, $elem["content"]); 
} 

看起來好像必須有更好的方法來做到這一點!任何人都可以想到一個?

數據來自我無法更改的結構不完整的XML文檔。

回答

1
$idxar=array(); 
foreach ($assoc_arr as $subar) 
    foreach ($subar as $item) 
    $idxar[$item['position']+0]=$item['content']; 

將工作,如果您的輸入數據是完美的。

編輯

如果您需要的按鍵不僅在數值上是正確的,而且在正確的順序,你必須用ksort($idxar)

+0

看我的編輯,如果你需要的鑰匙是我n順序。 –

+0

完美。謝謝!一旦它讓我接受,我會接受。 –

1

這裏後綴,這是另一種解決方案:

<?php 

$assoc_arr = 
    array("second" => array(
     array("position" => 4, 
       "content" => "Valiant"), 
     array("position" => 5, 
       "content" => "Hail") 
     ), 
    "first" => array(
     array("position" => 0, 
       "content" => "Hail"), 
     array("position" => 3, 
       "content" => "Victors"), 
     array("position" => 2, 
       "content" => "the"), 
     array("position" => 1, 
       "content" => "to") 
    ) 
); 

$order = array('first','second'); // this helps you create your own sort. E.g. position1, position2, etc 
$arr = array(); 

foreach($order as $ord) { 
    if(isset($assoc_arr[$ord])) { 
     $arr = array_merge($arr, $assoc_arr[$ord]); 
    } 
} 

$finalArray = array(); 

foreach($arr as $a) { 
    $finalArray[$a['position']] = $a['content']; 
} 

ksort($finalArray); 

print_r($finalArray); 

和小提琴適合你here