I am trying to create a website using codeigniter. I have two tables in the database. Theses tables are Category(Category Name, Category_Id) and Item(Item_Name, Category_id). Now, in my view I want of show the items in different tables for the different categories.
我正在尝试使用codeigniter创建一个网站。我在数据库中有两个表。这些表是Category(Category Name,Category_Id)和Item(Item_Name,Category_id)。现在,在我看来,我想在不同的表中显示不同类别的项目。
So far, I have come up with this, but obviously it is not working. The code in the model is this.
到目前为止,我已经想出了这个,但显然它没有用。模型中的代码是这样的。
$query = 'select category_id as id, category_name as name from category;';
$result = $this->db->query($query);
$data['category'] = $result->result_array();
foreach($data['category'] as $d)
{
$query = "select item_name as name from item where item_catagory_id = '{$d['id']}';";
$result = $this->db->query($query);
$data["{$d['id']}"] = $result->result_array();
}
$this->load->view('view', $data);
The code in the view is like this.
视图中的代码是这样的。
<?php foreach($category as $c):?>
<h2><?php echo $c['name']; ?></h2>
<table>
<tr>
<td>Item Name</td>
</tr>
<?php foreach($c['id'] as $d): ?>
<tr>
<td><?php echo $d['name'];?></td>
</tr>
<?php endforeach;?>
</table>
<?php endforeach;?>
But it says that " Invalid argument supplied for foreach()". It also says that the error is in this line :
但它说“为foreach()提供了无效的参数”。它还说错误在这一行:
<?php foreach($c['id'] as $d): ?>
1 个解决方案
#1
0
If I understand what you want to accomplish, Then here's what you want:
如果我明白你想要完成什么,那么这就是你想要的:
Change
$data["{$d['id']}"] = $result->result_array();
To:
$d['items'] = $result->result_array();
Then in your view, you'll simply do the second foreach like this:
那么在你看来,你只需要像这样做第二个foreach:
<?php foreach($c['items'] as $d): ?>
This way you're adding the items to the category itself with a known key.
这样,您可以使用已知密钥将项目添加到类别本身。
#1
0
If I understand what you want to accomplish, Then here's what you want:
如果我明白你想要完成什么,那么这就是你想要的:
Change
$data["{$d['id']}"] = $result->result_array();
To:
$d['items'] = $result->result_array();
Then in your view, you'll simply do the second foreach like this:
那么在你看来,你只需要像这样做第二个foreach:
<?php foreach($c['items'] as $d): ?>
This way you're adding the items to the category itself with a known key.
这样,您可以使用已知密钥将项目添加到类别本身。