Reputation: 4095
ok, I have a mysql table named "sales_records" like so:
User saleType
+-------+-------+------+
| Jeff | Sale_Closed |
+-------+-------+------+
| Jeff | Sale_null |
+-------+-------+------+
| Sean | sale_closed |
+-------+-------+------+
| Jeff | sale_closed |
+-------+-------+------+
| Sean | sale_closed |
+-------+-------+------+
| Mark | Sale_null |
+-------+-------+------+
| Mark | sale_closed |
+-------+-------+------+
| Josh | sale_closed |
+-------+-------+------+
| Josh | sale_closed |
+-------+-------+------+
I'm trying to count up each saleType for each User.. In other words.. Jeff has 2 "sale_closed" and 1 "sale_null. Mark has 1 "sale_closed" and 1 "sale_null", and so on..
and store it into an array.. (Json) like so.:
{"jeff":{"sale_closed":2,"sale_null":1},"sean":{"sale_closed":2},"Mark":{"sale_closed":1, "sale_null":1},"Josh":{"sale_closed":2}
Ok, so here's my attempt:
<?php
// assuming database connection has already been established..
$result = mysql_query("SELECT DISTINCT `USER' FROM `sales_records`");
while($row = mysql_fetch_assoc($result)) {
$user_array[] = $row['User'];
}
foreach ($user_array as $user) {
$json_array[$user] = mysql_query("SELECT saleType FROM sales_records WHERE user='$user'");
while ($row = mysql_fetch_array($json_array[$user])) { // AND HERE IS WHERE i GET STUCK!!!
$json_array[$user][$username][] = $row['saleType']; // I DON'T KNOW WHERE TO GO FROM HERE...
}
} // AM I APPROACHING THIS CORRECTLY?..
//...
// Once I have all the 'saleType's for each user, maybe I could use:
array_count_values()... or something.
?>
Upvotes: 2
Views: 99
Reputation: 43494
You can get all the data you need in a single query:
SELECT user, saleType, count(*) totalSales FROM sales_record
GROUP BY user, saleType
That will return all the results in 3 columns that should be easy to turn into JSon.
Upvotes: 5