Codeigniter:我如何向视图发送foreach语句?

时间:2011-09-22 23:16:17

标签: php codeigniter controller

控制器:

$categorys = array(
    '1234' => array('Car Audio','Car Subwoofers'), 
    '12'   => array('Car Stereos')
)

$category_id = $this->input->get('category_id');
$product_id  = $this->input->get('modelNumber');

if (array_key_exists($category_id,$categorys)) 
{
        foreach($categorys[$category_id] as $key => $value) 
    {
            echo $value;
    }
}

如何回应我的视图文件中 foreach 语句输出的 $ value

2 个答案:

答案 0 :(得分:3)

您可以将整个数组传递给视图并直接在视图中运行foreach,例如:

$data['array'] = array(/* etc. */);
$this->load->view('view', $data);

在视图中:

<?php foreach($array as $key => $value): ?>
  <p>The key is <?php echo $key; ?><br>
  The value is <?php echo $value; ?></p>
<?php endforeach; ?>

答案 1 :(得分:0)

<强>控制器

if (array_key_exists($category_id,$categorys)) 
{
     $query['cats'] = $categorys[$category_id];
}

查看

foreach($cats as $key => $value) 
{
   echo $value;
}