在会话变量中存储数组并使用codeigniter中的foreach检索它

时间:2014-12-29 06:29:26

标签: php codeigniter session

这是我在控制器中的代码

class placeorder_ajax extends CI_controller
{
 function __construct()
 {
    parent::__construct();
 }

//change text to check line endings
//new line endings

function index()
{       
//echo "hii";
//echo "<script>alert('dasdas');</script>";


//unset($_SESSION['cart']);
$data = array('product_id'=>$this->input->post('product_id'),
                'quantity'=>$this->input->post('quantity'),
                'unit'=>$this->input->post('unit'),
                'unit_rate'=>$this->input->post('unit_rate'));

                $this->session->set_userdata($data);

                    print_r($data);
?>
<table>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Amount</th>
<th>Action</th>
</tr>
<?php
$i=0;
foreach($_SESSION['cart'] as $cart)
{
    //echo "<pre>"; print_r($cart); echo "</pre>";
    $product_name = $this->db->query("SELECT product_name FROM product WHERE 
 product_id='".$cart['product_id']."'");
    echo "<tr>";
    echo "<td>".$product_name."</td>";
    echo "<td>".$cart['quantity']."</td>";
    echo "<td>".$cart['unit']."</td>";
    echo "<td>".$cart['unit_rate']."</td>";
    echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_cart'><img  
 src='assets/img/delete.png'/></a></td>";
    echo "</tr>";
    $i++;
 }
?>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table><?php
  }   
  }
  }

我不知道如何在codeigniter中的session varialbe中存储该数组并使用foreach循环检索它?它为foreach()提供了错误的未定义变量_SESSION和无效参数。那么我该如何解决这个问题呢?

我在codeigniter中执行此操作

如何在会话varialbe中存储该数组并使用foreach将其检索?

2 个答案:

答案 0 :(得分:0)

您的数组是一个关联数组。因此,使用foreach循环将其打印为键值对

foreach($_SESSION['cart'] as $key => $value) {

  //$key will be product_id, quantity etc
  //$value will be corresponding values
  echo "key: $key<br />value: $value";

  //just for formatting the output
  //this will just insert one more break
  echo "<br />";
}

答案 1 :(得分:0)

尝试做这样的事情

$myarray =  $_POST;
$_SESSION['myarray_insession'] = $myarray;

或者

$myarray = array('product_id'=>$this->input->post('product_id'),
                'quantity'=>$this->input->post('quantity'),
                'unit'=>$this->input->post('unit'),
                'unit_rate'=>$this->input->post('unit_rate'));


$_SESSION['myarray_insession'] = $myarray;

然后使用类似

的foreach
foreach($mysession as $row=>$value){

    }