我有两张 table
类别:
- cat_id
- 猫的名字
项目
- items_it
- 项目名称
- item_cat
我想得到这个结果:
Category->cat_name1
- item_name1
- item_name2Category->cat_name2
- item_name3
- item_name4
对于 PHP,我会选择这样的东西:
$query1 = 'SELECT *FROM Category';
foreach($query1 as $cat) {
$query2 = 'SELECT *FROM Items WHERE "item_cat" = $cat';
echo $cat;
foreach($query2 as $item) {
echo $item;
}
}
使用 CODEIGNITER 的最佳方法是什么?
最佳答案
下面是 Codeigniter 中使用您的架构的简单示例:
<?php
$this->db->select('*'); // select all columns
$this->db->from('Category'); // FROM table
$this->db->join('Items', 'Items.item_cat = Category.cat_id'); // INNER JOIN
$query = $this->db->get(); // GET RESULT
?>
要获取结果,您可以使用两种方法,要么以对象形式获取数据,要么以数组形式获取数据。
在 Array 中,使用 result_array()
方法,例如:
$result = $query->result_array();
echo "<pre>";
print_r($result); // will print all data in array
在 Object 中,使用 result()
方法,例如:
$result = $query->result();
echo "<pre>";
print_r($result); // will print all data in object
现在您可以按需要排序:
$newArray = array();
foreach ($result as $key => $value) {
$newArray[$value['cat_name']][] = $value; // sort as per category name
}
print_r($newArray); // will print all data against each category.
现在将您需要的结果打印为:
foreach ($newArray as $key => $value) {
echo $key."<br/>"; // print Category Name
foreach ($value as $final_value) {
echo $final_value['item_name']."<br/>"; // print all items against category
}
}
Query Builder Class 浏览文档,这将帮助您更多地了解如何利用 INNER
或 LEFT
加入 CI。
关于php - Codeigniter 加入两个表显示类别名称并列出所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43074992/