2013-09-20 61 views
0

我的程序中有五個不同的數組。所有的陣列長度相同。對於這個例子,假設所有的數組都包含6個項目。第一個數組array1 [0]應該與其他數組的索引值0配對。所以我得到一個所有索引0的數組,所有索引爲1和2,3,4以及索引爲5的數組。在PHP中將五個數組合併到五個「組合」數組中

如何做到這一點?

添加更多詳細信息: 我有以下包含shopping_cart中的項目信息的數組。

$nameArray - contains the names of the products in the basket 
$productIdArray - contains the id_numbers of the products in the basket 
$priceArray - array of the prices for each item in the basket 
$quantityArray - array which holds the quantity of each item in the basket 

等等,等等

我會喜歡改變輸出,所以可以發送包含表示單品各自與它的所有值數組a multidimensionel陣列用於在AJAX發送它的呼...

希望它是有道理的。 :)

+2

確實如此:你怎麼看,你有什麼嘗試? –

+0

即使存在可變數量的元素,也請查找我的答案以獲得一般解決方案。 – footy

回答

1

我只用了四個數組,因爲它應該足以解釋這個過程。這裏可能有更優雅的解決方案,但需要更多思考。

重點是我覺得最容易考慮這樣的問題,如表格。你的實例實際上比較簡單。你有行的數組,你想要將它們轉換爲列的數組。看看我的解決方案。

<?php 

$one = array('brown', 'green', 'red', 'yellow', 'orange', 'purple'); 
$two = array('cupcake', 'honeycomb', 'icecream', 'chocolate', 'jellybean', 'milkshake'); 
$three = array('monday', 'tuesday', 'wednesday', 'thrusday', 'friday', 'saturday'); 
$four = array('january', 'february', 'march', 'april', 'august', 'september'); 

//put all of your arrays into one array for easier management 
$master_horizontal = array($one, $two, $three, $four); 
$master_vertical = array(); 

foreach ($master_horizontal as $row) { 
    foreach ($row as $key => $cell) { 
    $master_vertical[$key][] = $cell; 
    } 
} 

echo "<PRE>"; 
print_r($master_vertical); 

返回...

Array 
(
    [0] => Array 
     (
      [0] => brown 
      [1] => cupcake 
      [2] => monday 
      [3] => january 
     ) 

    [1] => Array 
     (
      [0] => green 
      [1] => honeycomb 
      [2] => tuesday 
      [3] => february 
     ) 

    [2] => Array 
     (
      [0] => red 
      [1] => icecream 
      [2] => wednesday 
      [3] => march 
     ) 

    [3] => Array 
     (
      [0] => yellow 
      [1] => chocolate 
      [2] => thrusday 
      [3] => april 
     ) 

    [4] => Array 
     (
      [0] => orange 
      [1] => jellybean 
      [2] => friday 
      [3] => august 
     ) 

    [5] => Array 
     (
      [0] => purple 
      [1] => milkshake 
      [2] => saturday 
      [3] => september 
     ) 

) 
+0

非常感謝您的先生。 – Zahrec

0

既然你不貼你寫成現在我會給出一個一般性解釋任何代碼。這看起來更像是一個家庭作業問題,所以我不會發布工作解決方案。

let there be N arrays with variable number of elements in it. 
Let Answer_Array be an array of arrays. 
loop i=0 to N 
    tmpArray = Arrays[i] 
    loop j=0 to length(N)-1 
     add tmpArray[j] to Answer_Array[j] 
    end loop 
end loop 

如果你將原始輸入結合到一個數組數組中,並將最終輸出結果存儲在一個數組數組中,這很簡單。

+0

這不是作業。這是我正在開發的一個網上商店系統。 – Zahrec