
Question:
I am having trouble finguring out how to use the table data like I need to... my table consists of a category name column (which has the same value for many subcategories) and the other column contains subcategory names.
For example:
col1 col2
------------------
apples fruits
oranges fruits
pears fruits
honda cars
volvo cars
audi cars
I am trying to write a select statement that selects all the data from the database and prints out the category name once ONLY, while printing out all subcategories that, that particular category name includes.
Something like:
<strong>Fruits:</strong>
<ul><li>Apples</li> <li>Oranges</li> <li>Pears</li> </ul><strong>Cars:</strong>
<ul><li>Honda</li> <li>Volvo</li> <li>Audi</li> </ul>Answer1:
SELECT
col2,
GROUP_CONCAT(col1 SEPARATOR ',') as stuff
FROM table1
GROUP BY col2
If you want the '-' in front of the names you can use CONCAT('-',col1)
instead of col1
.
This php code will transform the result into a 1 dimensional array
$conn = new mysqli('host','user','pass','db_name');
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
if (!($rs = $conn->query("
SELECT
col2,
GROUP_CONCAT(col1 SEPARATOR ',') as stuff
FROM table1
GROUP BY col2
"))) {
printf("Error: %s\n", $conn->error);
exit();
}
$result = array();
while ($row = $rs->fetch_object()){
$result[] = $row->col2;
if(!empty($row->stuff)) $result = array_merge($result,explode(',',$row->stuff));
}
Answer2:What you is it recommended. Moreover, it would make your life with an array very difficult. Consider trying something like this:
$query = mysql_query("SELECT * FROM table");
$array = array();
while($row = mysql_fetch_assoc($query)) {
$cat = $row['col2'];
$item = $row['col1'];
$array[$cat] = $item;
}
Now you have an array with categories as keys and items as values for each of those keys.
Good luck!