我在 mysql 中有 2 个表;
项目
类别
items
有一个 cat_id
列指向它们在 categories
表中的类别
我使用下面的查询来获取项目和类别;
SELECT a.id, a.cat_id, a.rest_id, a.name, a.description, a.price, b.rest_id, b.name
FROM items a, categories b
WHERE a.cat_id = b.id AND b.rest_id = 1
我想使用 ng-repeat 生成如下列表;
Category A
Item (belongs to cat A)
Item (belongs to cat A)
Item (belongs to cat A)
Category B
Item (belongs to cat B)
Item (belongs to cat B)
Item (belongs to cat B)
如何使用 ng-repeat
实现此目的
到目前为止我已经有了这个,但没有用;
<div class="results-group" ng-repeat="(key, value) in fetchedData">
<h3 style="text-align: left;"></h3>
<ul>
<li ng-repeat="data in value">
</li>
<ul>
</div>
谢谢。
$query1 = "SELECT * FROM categories WHERE rest_id = $restaurant_id";
$select_all_cats = mysqli_query($connection, $query1);
$rows = $select_all_cats -> num_rows;
$arr1 = array();
$arr2 = array();
if($rows > 0) {
while($rows = mysqli_fetch_assoc($select_all_cats)) {
$arr1[] = $rows;
$cat_id = $rows['id'];
$query2 = "SELECT * FROM items WHERE cat_id = $cat_id";
$select_all_items = mysqli_query($connection, $query2);
$rowx = $select_all_items -> num_rows;
if($rowx > 0) {
while($rowx = mysqli_fetch_assoc($select_all_items)) {
$arr2[] = $rowx;
}
}
}
}
最佳答案
首先,您应该删除 PHP 中的嵌套查询。循环/嵌套查询是一种反模式,您应该学会识别它并通常用利用连接的适当查询替换它。
像这样的东西应该在 PHP 端起作用:
// array to store results
$item_array = array();
$query = "SELECT
cat.name AS cat_name,
i.id AS id,
i.name AS name,
i.description AS description,
i.price AS price
FROM categories AS cat
INNER JOIN items AS i
ON cat.id = i.id
WHERE i.rest_id = ?
ORDER BY cat_name ASC";
$result = mysqli_query($connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
// read into 2D array
$item_array[$row['cat_name']][] = $row;
}
}
需要注意的是,我们这里构建的是一个二维数组,类别名称是第一维。然后,您可以将其与 ng-repeat 一起使用,如下所示。请注意,我将在此处将 $item_array
中的数据称为 itemData
。另请注意,itemData
在为 javascript 格式化时将采用对象的形式。 itemData
上的每个类别“属性”都将包含项目记录的数字索引数组。
<div class="results-group" ng-repeat="(cat, items) in itemData">
<h3 style="text-align: left;">{{cat}}</h3>
<ul>
<li ng-repeat="item in items">
<!-- output content from item here like {{item.name}} and similar -->
</li>
<ul>
</div>
关于php - ng-repeat 分组与 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553146/