传递关联数组以使用foreach查看和访问其中的值

时间:2015-01-10 10:09:45

标签: php codeigniter

这是我在控制器中的代码......

function print_dm($delivery_memo_id){
    $data1=array();

    $query=$this->db->query("select de.*, pr.* from phppos_delivery_memo de inner join 
    phppos_productdetails pr  on de.delivery_memo_id=pr.delivery_memo_id WHERE 
     de.delivery_memo_id=$delivery_memo_id");

    if($query->num_rows() > 0)
  {
  foreach ($query->result() as $row)
  {

    $data1[]=$row->product_id;
    $data1[]=$row->product_name;
    $data1[]=$row->quantity;
    $data1[]=$row->unit;
    $data1[]=$row->unit_rate;


  }
}
else
{
$data1 = array();
 }

 $this->load->view('delivery_memo/print_layout',$data1);

}

当我print_r $ data1时,我得到了这个......

 Array ( [0] => 1 [1] => Zinc Sulphate [2] => 1 [3] => 1 [4] => 100 [5] => 4 [6] => Copper 
 Sulphate [7] => 1 [8] => 12 [9] => 100 [10] => 9 [11] => Sulphur 80% WDG [12] => 1 [13] => 1 
 [14] => 100 )

我将其传递给上面查看。但是如何在那里访问它或者我应该更改控制器中的代码?

我在该数组中获得多条记录

2 个答案:

答案 0 :(得分:2)

只需将查询结果传递给查看:

function print_dm($delivery_memo_id){
    $data1=array();

    $query=$this->db->query("select de.*, pr.* from phppos_delivery_memo de inner join 
    phppos_productdetails pr  on de.delivery_memo_id=pr.delivery_memo_id WHERE 
     de.delivery_memo_id=$delivery_memo_id");

    $this->load->view('delivery_memo/print_layout', array('data1' => $query->result()));
}

然后,您应该可以在视图中访问$data1变量,例如:

<?php foreach ($data1 as $row) { echo $row->product_id . "\n"; } ?>

答案 1 :(得分:1)

显然,您并不了解如何访问传递给视图的数据。您将一个数组传递给您的视图,在一个视图中不会有$data1变量,在您传递的数组中会有像变量一样命名的变量。所以你应该传递这样的数据:

$this->load->view('delivery_memo/print_layout',array('data1' => $data1));

之后可以在视图中访问$data1

var_dump($data1);

有关此处观看次数的更多信息:https://ellislab.com/codeigniter/user-guide/general/views.html