2012-11-08 70 views
0

我需要重建一個數組。原來這裏是數組:PHP重構陣列

array(8) { 
     [0] => array(1) 
     { 
      ["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D" 
     } 

     [1] => array(1) 
     { 
      ["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528" 
     } 

     [2] => array(1) 
     { 
      ["L_STATUS0"] => string(9) "Completed" 
     } 

     [3] => array(1) 
     { 
      ["L_STATUS1"] => string(9) "Completed" 
     } 
} 

我想重建它是這樣:

array(2) { 
     [0] => array(2) 
     { 
      ["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D" 
      ["L_STATUS0"] => string(9) "Completed" 
     } 
     [1] => array(1) 
     { 
      ["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528" 
      ["L_STATUS1"] => string(9) "Completed" 
     } 
} 

注意兩個比賽用數字表示的按鍵......這是在所有可能的?

編輯:

這裏是我的代碼我使用:

 foreach($comparison as $key => $val) { 
     $findme1 = 'L_TRANSACTID'.$i++; 
     $findme2 = 'L_STATUS'.$c++; 
     $arrDisable = array($findme1,$findme2); 
     if(in_array($key, $arrDisable)) { 
      unset($comparison[ $key ][$val]); 
     } 
      if(in_array($key, $arrDisable)) { 
     unset($comparison[ $key ][$val]); 
     } 
     } 
+0

是的。但是你需要編寫自己的代碼來完成這個任務。也就是說,沒有單一的,神奇的PHP函數。 –

+0

當然,這是可能的。你試過什麼了?我們不在這裏爲你做你的工作,所以顯示你的嘗試。 –

+0

我嘗試使用的代碼。 –

回答

1

試試這個

$labels = array('L_TRANSACTIONID', 'L_STATUS'); 
$res = array(); 
foreach($arr as $val) { 
    $key = str_replace($labels, '', key($val)); 
    $res[$key] = isset($res[$key]) ? array_merge($res[$key], $val) : $val; 
} 
print_r($res); 

http://codepad.org/MwqTPqtA

+0

哇...非常感謝! –

0

如果你有一定的載體cointains對L_TRANSACTIONIDn/L_STATUSn鍵,也就是說,對於每個事務ID,都有一個相應的狀態,你可以做的是獲取id /狀態記錄的數目(它應該等於初始數組的長度,除以2),並通過增加當前元素數量來組合結果。

可能是這個樣子:

$numItems = sizeof($myInitialArray)/2; 
$newArray = array(); 

for($i = 0; $i < $numItems; $i++) 
{ 
    $itemID = $i * 2; // since we're getting id/status pairs, we're using a step equal to 2 

    $newArray[] = array(
     ("L_TRANSACTIONID" . $i) => $myInitialArray[$itemID], // this is the id value 
     ("L_STATUS" . $i) => $myInitialArray[$itemID + 1] // this is the status for that id 
    ); 
} 

希望這有助於。祝你有美好的一天!