将数组存储在会话变量中,并在代码点火器中使用foreach检索它


Storing array in session variable and retrieving it using foreach in codeigniter

这是我在控制器中的代码

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
  }   
  }
  }

我不知道如何将该数组存储在代码点火器的会话变量中并使用 foreach 循环检索它?它给出了错误未找到的变量_SESSION和为 foreach() 提供的无效参数。那么我该如何解决这个问题呢?

我在编码点火器中执行此操作

如何将该数组存储在会话变量中并使用 foreach 检索它?

尝试做这样的事情

$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($mysession as $row=>$value){
    }

数组是一个关联数组。因此,使用 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 />";
}