2015-05-05 55 views
1

從我的數據庫接收數據後,我把這些數據逐行放入一個數組中,所以我可以稍後訪問這個數組。但我目前使用下面這個數組:PHP array:orderID with multiple orderdetailIDs

JSON樣品

[{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":4,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":false,"extrasPrice":0}, 

{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":5,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":3,"extras":false,"extrasPrice":0}] 

正如你可以看到我用了2次單編號(5),每次這都屬於相同的orderID的ORDERDETAILS,在這個例子orderID 5.

現在這個數組並不是很好,因爲當使用角度我有困難顯示每個orderID的訂單以及屬於該orderID的orderdetails。

我想表明的是對每個單編號:

是這樣的:在單編號的foreach orderdetailID。

的orderID 5 =>所有其ORDERDETAILS的(= orderdetailID 4和5 orderdetailID的數據)

所以創建陣列時,我怎樣才能添加ORDERDETAILS的陣列到對應的行的orderID?

例如

[{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare", {"orderdetailID":4,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":false,"extrasPrice":0},{"orderdetailID":5,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":3,"extras":false,"extrasPrice":0}] 
+0

你需要遍歷它並創建一個嵌套的結構。編號可能在PHP方面做到這一點,但你可以在JS方面做到這一點,如果你想。 – prodigitalson

+0

是的,我知道我必須循環它,但我不知道如何創建所需的數組 – Sesamzaad

回答

2

您需要循環,並創建一個嵌套的結構。編號可能在PHP端做到這一點,但你可以在JS端做到這一點,如果你想

$orders = array(); 

// lets create an array of the keys that belong to the "order" 
// we will use this to extract the other keys for the details 
$orderKeys = array('orderID', 'customerID', 'customerName', 'orderDate', 'orderDeliveryDate', 'orderStatus'); 
$orderKeys = array_combine($orderKeys, $orderKeys); 

// loop over each row in the db result set - not sure 
// what driver you are using so you can replace this loop 
// with whatever kind of loop makes sense 
foreach($resultSet as $row) { 
    $id = $row['orderID']; 

    if (!isset($orders[$id]) { 
     // this is the first record in our result set for this 
     // orderID, so lets get the data for the order and put it 
     // into the orders array, using the orderID as the array key 
     $orders[$id] = array_intersect_key($row,$orderKeys); 

     // lets also add an array for all our details items 
     // you could use a key other than details just depends on what 
     // you want to call it 
     $orders[$id]['details'] = array(); 
    } 

    // add the detail item to the order 
    $orders[$id]['details'][] = array_diff_key($row, $orderKeys); 
} 

// create the JSON - use array_values to reindex the array 
// since using the orderID as the key is not relevant on the JS side 
$ordersJSON = json_encode(array_values($orders)); 

// now do whatever you need to do with the JSON 
+0

我編輯了一下,但這導致我正確的解決方案!非常感謝 – Sesamzaad