这是将两个SQL查询组合到数组的正确方法吗?
注意:我知道SQL JOIN,但我需要使用两个查询。
见下文:
$query = "SELECT * FROM categories WHERE takeawayID = :TakeawayID";
$statement = $this->db->prepare($query);
$statement->bindValue(':TakeawayID', $takeawayID, PDO::PARAM_STR);
$statement->execute();
$data['rowCats'] = $statement->fetchall(PDO::FETCH_CLASS);
$categories = array();
foreach ($data['rowCats'] as $cat) {
$temp_categories = array();
$temp_categories['id'] = $cat->id;
$temp_categories['name'] = $cat->name;
$num = $cat->id;
$query = "SELECT * FROM items WHERE category_id = :category_id";
$statement = $this->db->prepare($query);
$statement->bindValue(':category_id', $num, PDO::PARAM_STR);
$statement->execute();
$data['rowItem'] = $statement->fetchall(PDO::FETCH_CLASS);
foreach ($data['rowItem'] as $Item) {
$temp_categories['item']['name'][] = $Item->name;
}
$categories[] = $temp_categories;
}
$ categories数组现在可以传递给查看文件(模板)
在视图文件中,我应该能够做到这样的事情:
<?php foreach($categories as $category): ?>
<table border=0 Cellspacing='0'>
<tr>
<td>
<?php echo $category['name']; ?>
</td>
</tr>
<?php foreach ($category['items'] as $item): ?>
<tr>
<td>
<?php echo $item['name']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
答案 0 :(得分:2)
您是否有理由将结果作为类而不是关联数组获取?将FETCH_CLASS
更改为FETCH_ASSOC
将允许您直接将项目名称添加到第一个查询的结果中,而无需使用临时数组。
在该foreach循环中,您在语义上只有一个具有多个名称的项目。我认为这不是你想要做的,所以你应该写下这样的东西:
foreach ($data['rowItem'] as $Item) {
$temp_categories['item'][] = array('name' => $Item->name);
}