Php 来自数据库查询的数组中的数组
我有一个订单表(Php 来自数据库查询的数组中的数组,php,mysql,sql,arrays,codeigniter,Php,Mysql,Sql,Arrays,Codeigniter,我有一个订单表(tbl\u订单) 每行代表一个产品。 订单可以有一行或多行 例如,发票139813018020有两种不同的产品Product35和product43,这是两行。这是一整份订单 我使用的查询如下: SELECT invoice, productID, qty, currentPrice FROM tbl_orders return $query->result_array() // codeigniter 其输出如下: Array ( [0] => Array
tbl\u订单
)
每行代表一个产品。
订单可以有一行或多行
例如,发票139813018020
有两种不同的产品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
)
)
我需要一份订单和该订单的产品
我需要阵列看起来像这样或类似:
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>";
//从数据库中获取数组
$arr=$query->result_array();
//初始化一个新数组
$newarr=array();
//循环遍历数据库数组并向新数组添加条目
外汇($arr作为$entry){
$newarr[$entry['invoice'][]=数组(
'productID'=>$entry['productID'],
“数量”=>$entry[“数量”],
'currentPrice'=>$entry['currentPrice']
);
}
//输出新数组
回显“.print\u r($newarr,true)。”;
我会选择不同的发票号,然后在生成的数组中循环,查询一个发票号的产品ID、数量和价格
// 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>";