gpt4 book ai didi

php - 来自数据库查询的数组内数组

转载 作者:行者123 更新时间:2023-11-30 00:20:30 25 4
gpt4 key购买 nike

我有一个订单表 (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
)

)

我需要一个订单以及该订单的产品

我需要数组看起来像这样或类似的:

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 索引。

// 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>";

关于php - 来自数据库查询的数组内数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23282076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com