How to combine data using php
Currently my MySQL data is stored as shown below
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
How to combine, explode, combine and sum it like this in php?
puma 485.00
adidas 350.00
reebook 70.00
umbro 56.00
+2
a source to share
2 answers
I don't know what your result set looks like, but the logic should be the same:
$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);
+1
a source to share
I have a quick question about your data structure: why the heck is your data structure like this?
To ensure that your data is normalized (avoid data duplication), create items that refer to orders, product table, etc.
products
--------
id
name
price
orders
------
id
created
order_items
------------
id
order_id
product_id
quantity
Now I can make inquiries like giving me the 5 biggest order totals. What is the most popular product I sell? Let me change the name of this product, but not all of my data falls apart.
+2
a source to share