2014-04-25 73 views
0

我有一個訂單表(tbl_orders)。數組中的數組查詢

+------------------------------------------------+ 
|invoice  | productid | qty | currentPrice | 
+------------------------------------------------+ 
|139813018020 | 35  | 4 | 199   | 
|139813018020 | 43  | 1 | 329   | 
|139813307433 | 22  | 4 | 399   | 
|139813307433 | 15  | 1 | 150   | 
|139813307477 | 63  | 1 | 499   | 
+------------------------------------------------+ 

每行代表一個產品。 訂單可能有一個或多個行。

例如,發票139813018020有2個不同的產品。 Product35product43,它們是兩行。這是一個整個訂單

我使用的是這樣的查詢:

SELECT invoice, productID, qty, currentPrice FROM tbl_orders 
return $query->result_array() // codeigniter 

,它輸出以下內容:

Array 
(

[0] => Array 
    (
     [invoice] => 139813018020 
     [productID] => 35 
     [qty] => 4 
     [currentPrice] => 199 
    ) 

[1] => Array 
    (
     [invoice] => 139813018020 
     [productID] => 43 
     [qty] => 1 
     [currentPrice] => 329 
    ) 

[2] => Array 
    (
     [invoice] => 139813307433 
     [productID] => 22 
     [qty] => 4 
     [currentPrice] => 399 
    ) 

[3] => Array 
    (
     [invoice] => 139813307433 
     [productID] => 15 
     [qty] => 1 
     [currentPrice] => 150 
    ) 
[4] => Array 
    (
     [invoice] => 139813307477 
     [productID] => 63 
     [qty] => 1 
     [currentPrice] => 499 
    ) 

) 

我需要ONE訂單和產品順序

我需要的陣列看起來像這樣或類似的東西:

Array 
(

[0] => Array 
    (
     139813018020 => Array 
     (
      [0] => Array 
       (
        [productID] => 35 
        [qty] => 4 
        [currentPrice] => 199 
       ) 
      [1] => Array 
       (
        [productID] => 43 
        [qty] => 1 
        [currentPrice] => 329 
       ) 

     ) 
    ) 
[1] => Array 
    (
     139813018033 => Array 
     (
      [0] => Array 
       (
        [productID] => 22 
        [qty] => 4 
        [currentPrice] => 399 
       ) 
      [1] => Array 
       (
        [productID] => 15 
        [qty] => 1 
        [currentPrice] => 150 
       ) 

     ) 
    ) 

[2] => Array 
    (
     139813018077 => Array 
     (
      [0] => Array 
       (
        [productID] => 63 
        [qty] => 1 
        [currentPrice] => 499 
       ) 
     ) 
    ) 
) 

我使用php,mysqli和codeigniter。

+0

我將通過所得陣列選擇不同的發票號,然後循環和查詢產品ID,數量和價格之間的所述一個發票號碼 –

回答

0

一種方法是循環訪問您的數據庫數組,並建立一個新的數組,其鍵設置爲invoice數字。這樣,每張發票號碼鍵都會引用該發票中訂購的產品數組。

請注意,與您所需的輸出相比,下面的方法具有更少的深度級別。根數組的鍵是發票號碼,而不是0索引。

// get the array from your database 
$arr=$query->result_array(); 

// initialize a new array 
$newarr=array(); 

// loop through database array and add entries to new array 
foreach ($arr as $entry) { 
    $newarr[$entry['invoice']][] = array(
    'productID' => $entry['productID'], 
    'qty'   => $entry['qty'], 
    'currentPrice' => $entry['currentPrice'] 
); 
} 

// output new array 
echo"<pre>".print_r($newarr,true)."</pre>";