I must to create a menù that contain a list of subcategory items group by mother category and take these values from product table:
Category
SubCategory SubCategoryCategory
SubCategoryI got this:
<?php
$query_cat = $db->prepare("SELECT * FROM products GROUP BY category ORDER BY category");
$query_cat->execute();
print '<li><strong>'. $category . '</strong></li>'; //Category
while ($cat_row = $query_cat->fetch()) { //Subcategory
print '<li><a href="/category/'. $cat_row['4'] .'">'. $cat_row['4'] .'</a></li>';
}
?>
The products
table structure is
ID, name, stars, brand, category, priceavg, first-category
How i can get the category name and put in top of the element?
Thanks to all for the help provided.
You can use array_group_by function as below
$query_cat = $db->prepare("SELECT name, category, first_category FROM products ORDER BY category");
$query_cat->execute();
$rows = $query_cat->fetchAll(PDO::FETCH_ASSOC);
$items = array_group_by($rows, 'first_category');
foreach($items as $key => $value) {
echo '<li><strong>' . $key . '</strong></li>';
foreach($value as $row) {
echo '<li><a href="/category/'.$row['category'].'">'.$row['category'].'</a></li>';
}
}
The array_group_by
is a function that groups an array by a key or set of keys shared between all array members. Once you've retrieved your SQL data as an associative array, you can apply the array_group_by
function an obtain an array of array such as categories and subcategories.
After the array_group_by
this is a sample result of how your $items
array is structured https://3v4l.org/5WkDH
Final live example here https://3v4l.org/cg9NN
Tip Why is SELECT * considered harmful? Consider to not use SELECT * FROM
in your queries
EDIT If you want compatibility to PHP lower than 5.3, you just have to change []
with array()
short array notation. Live example here https://3v4l.org/0VUn7 (tested from PHP 4.3 to latest)