如何在视图中发送一个我不知道名称的变量


How to send a variable whose name I don't know in the view?

我正在尝试使用codeigniter创建一个网站。我在数据库中有两个表。这些表是Category(Category Name, Category_Id)和Item(Item_Name, Category_Id)。现在,在我看来,我想在不同的表中显示不同类别的项目。

到目前为止,我已经想出了这个,但显然它不起作用。模型中的代码如下:

$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);

视图中的代码如下:

<?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;?>

但是它说"为foreach()提供了无效参数"。它还指出错误在这一行:

<?php foreach($c['id'] as $d): ?>

如果我明白你想要完成什么,那么这就是你想要的:

改变
$data["{$d['id']}"] = $result->result_array();

:

$d['items'] = $result->result_array();

然后在您的视图中,您只需像这样执行第二次foreach:

<?php foreach($c['items'] as $d): ?>

通过这种方式,您可以使用已知键将项目添加到类别本身。

相关文章: