foreach语句只返回1项

时间:2011-09-24 13:31:34

标签: php session codeigniter foreach

我正在使用会话来存储已查看的产品,但在查询数据库时打印出所有项目时遇到问题。

控制器

$hello_world = $this->session->all_userdata();


foreach($hello_world as $key=>$product_id) {
 $query['products']  = $this->Global_products->globalFindProducts($product_id);

  echo $product_id; // Right here it echos all the items in the session.

 }

模型

function globalFindProducts($product_id) 
{
$this->db->join('price','product.modelNumber = price.modelNumber','left')->where('product.modelNumber',$product_id);
$this->db->group_by('product.modelNumber');
$query = $this->db->get('by.product');
return $query->result();
}

查看

<?php foreach($products as $product) { ?>
<div><?php echo $product->name; ?></div>
<?php } ?>

在我看来,我只能看到一个项目,而不是所有项目。有人可以就你如何解决这个问题向我提出建议吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

试试这个,我还没有在CodeIgniter中编码,所以它是最好的猜测:

控制器

$hello_world = $this->session->all_userdata();

foreach($hello_world as $key=>$product_id) {
    $query['products'][]  = $this->Global_products->globalFindProducts($product_id);
    echo $product_id; // Right here it echos all the items in the session.
}

注意:这里我将$query['products']作为一个数组,因此所有结果都来自于 存储$this->Global_products->globalFindProducts($product_id);

答案 1 :(得分:0)

您在哪里将数据库结果共享给视图?

通常情况下,您需要使用以下内容:

$data['hello_world'] = $this->session->all_userdata();

然后在调用视图时,包含该数据数组:

$this->load->view('someview', $data);

因此,在您的视图中,您可以运行for循环:

<?php foreach($hello_world as $product) { ?>
<div><?php echo $product->name; ?></div>
<?php } ?>
相关问题