这是我在控制器中的代码
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
)
)
答案 0 :(得分:0)
您需要使用index()
函数将$post_array
数组返回到主脚本,否则它在主脚本的范围内不可见;要做到这一点,首先需要相应地更改index()
函数定义,最后添加它:
return $post_array();
然后,您可以在index()
语句之前将foreach
调用到主脚本中,以便将其返回值存储到$post_array
中:
$post_array = index();
答案 1 :(得分:0)
总是更好地在将任何数据存储到会话之前对其进行序列化,它可以简单地作为字符串放入会话中。无论何时需要,都可以轻松访问和反序列化。