这是我在控制器中的代码
function index()
{
$data=array();
$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',$data);
$post_array[]=$this->session->userdata('data');
?>
<table>
<tr>
<th>Product Name</th>
<th>Quantity </th>
<th>Unit </th>
<th>Unit Rate</th>
<th>Action</th>
</tr>
<?php
$i=0;
foreach($post_array as $cart)
{
//echo "<pre>"; print_r($cart); echo "</pre>";
$query = $this->db->query("SELECT product_name FROM phppos_product WHERE
product_id='".$post_array[$i]['product_id']."'");
foreach ($query->result() as $row)
{
$product_name=$row->product_name;
}
echo "<tr>";
echo "<td>".$product_name."</td>";
echo "<td>".$post_array[$i]['quantity']."</td>";
echo "<td>".$post_array[$i]['unit']."</td>";
echo "<td>".$post_array[$i]['unit_rate']."</td>";
echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_cart'><img
src='images/close.png'/></a></td>";
echo "</tr>";
$i++;
}
?>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table><?php
}
我正在会话中存储$data
数组,即单维数组,并尝试将其附加到二维数组,即 $post_array['cart'][]
.我正在尝试使用循环foreach
检索它。它给了我undefined index
和illegal offset string
等错误。那么我该如何解决这个问题呢?
我编辑了我的代码。这给了我我想要的,但它是错误的。我不知道谁能告诉我?
这是我的print_r($post_array)输出
Array
(
[0] => Array
(
[product_id] => 2
[quantity] => 1
[unit] => 12
[unit_rate] => 100
)
)
你需要
你的index()
函数将你的$post_array
数组返回到主脚本,否则它在主脚本的作用域中是不可见的;为此,你首先需要相应地更改你的index()
函数定义,方法是在末尾添加以下内容:
return $post_array();
然后,您可以在foreach
语句之前将index()
调用到主脚本中,以便将其返回值存储到$post_array
:
$post_array = index();
最好在
将任何数据存储到会话之前对其进行序列化,它可以简单地作为字符串放入会话。在需要时可以轻松访问和反序列化它。