2

目前我的 MySQL 数据存储如下

product             | total
------------------------------------------
puma,adidas         | 100.00,125.00     
puma                | 80.00
reebok,adidas,puma  | 70.00,100.00,125.00
adidas,umbro        | 125.00,56.00      

如何在php中像这样组合、分解、合并和总计?

puma     485.00
adidas   350.00
reebook  70.00
umbro    56.00
4

2 回答 2

2

我有一个关于你的数据结构的快速问题:为什么你的数据结构是这样的???

话虽如此,请查看规范化您的数据(避免重复数据),创建属于订单的行项目,产品表等......

products
--------
id
name
price


orders
------
id
created


order_items
------------
id
order_id
product_id
quantity

现在我可以进行查询,比如给我订单中最大的 5 个总数我卖的最受欢迎的商品是什么? 让我更改此产品的名称,但不要让我的整个数据崩溃。

于 2010-04-27T16:14:00.680 回答
1

我不知道你的结果集是什么样的,但逻辑应该是一样的:

$combined = array();
foreach ($results as $result) {
    $productsArr = split(",", $result['product']);
    $totalsArr = split(",", $result['total']);

    // we'll assume both arrays are always the same size
    $prodCount = count($productsArr);
    for($i = 0; $i < $prodCount; $i++) {
        $combined[$productsArr[$i]] += (float)$totalsArr[$i];
    }
}
print_r($combined);
于 2010-04-27T16:06:14.957 回答