我有一张订单表(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 |
+------------------------------------------------+
每行代表一个产品。 订单可能包含一行或多行。
EG。发票139813018020
有2种不同的商品。 Product35
和product43
,分为两行。这是一个完整的订单
我正在使用这样的查询:
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 :(得分: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>";