当我将不同供应商的(随机添加的)产品添加到购物车时。
前:
数据表。
VENDORS TABLE
| vendorid | vendorname |
-------------------------
| 1 | A |
| 2 | B |
| 3 | C |
-------------------------
PRODUCTS TABLE
| productid | productname | postbyvendor(FK) |
----------------------------------------------
| 1 | Shirt1 | 1 |
| 2 | Shirt2 | 1 |
| 3 | Shirt3 | 2 |
| 4 | Shirt4 | 2 |
| 5 | Pants1 | 1 |
| 6 | Pants2 | 3 |
点击添加到购物车6次。
1st Add Shirt1 from Vendor A to cart
2nd Add Shirt3 from Vendor B to cart
3rd Add Pants2 from Vendor C to cart
4th Add Shirt2 from Vendor A to cart
5th Add Pants1 from Vendor A to cart
6th Add Shirt4 from Vendor B to cart
购物车视图显示如下。
<li>Shirt1</li>
<li>Shirt3</li>
<li>Pants2</li>
<li>Shirt2</li>
<li>Pants1</li>
<li>Shirt4</li>
我想显示这样的结帐详情。
<li>Vendor Name : A</li>
<li>Shirt1</li>
<li>Shirt2</li>
<li>Pants1</li>
<li>Vendor Name : B</li>
<li>Shirt3</li>
<li>Shirt4</li>
<li>Vendor Name : C</li>
<li>Pants2</li>
我的查询。
$statement = $mysqli_conn->prepare("SELECT productname, postbyvendor FROM products_tbl WHERE productname = ? order by postbyvendor asc");
我尝试过的代码。
foreach($_SESSION["products"] as $product){
$product_name = $product["productname"];
$vendorsid = $product["postbyvendor"];
$cart_box = "<li>$vendorsid $product_name</li>";
}
显示如下:
<li>1 Shirt1</li>
<li>2 Shirt3</li>
<li>3 Pants2</li>
<li>1 Shirt2</li>
<li>1 Pants1</li>
<li>2 Shirt4</li>
赞赏。
答案 0 :(得分:2)
我想如果我这样做,我会创建一个函数来收集供应商及其商品,然后循环显示它们,例如:
function getVendors()
{
foreach($_SESSION["products"] as $product) {
$org[$product["postbyvendor"]][] = $product["productname"];
}
return (!empty($org))? $org : array();
}
foreach(getVendors() as $vendor => $prods) {
echo "<li>{$vendor}</li>";
echo "<li>".implode("</li><li>",$prods)."</li>";
}