繁体   English   中英

将关联数组附加到另​​一个数组

[英]appending associative array to another array

$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['cart'][]=$this->session->userdata('data');

我想将$ data附加到$ post_array。 我该如何使用Codeigniter?

我正在使用此代码创建购物车,并在其中存储客户添加到会话中的每个产品。 并希望在单独的表格中显示用户添加的所有产品。

您可以简单地将数据分配到购物车数组。

$post_array['cart'][] = $data;

以后,如果要遍历,可以使用以下命令:

foreach ($post_array['cart'] as $item) {
    echo 'Id of product: ' . $item['product_id']."<br />";
    echo 'Quantity: ' . $item['quantity']."<br />";
    //and so on...
}

但是我想,您想将其添加到会话中,而不是用于发布。

编辑

基于OP评论。 您总是会覆盖$ _SESSION ['data']变量。 因此,将其添加为新数组:

//Set the data
$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'));
//Get the cart
$cart = $this->session->userdata('data');
//Add data to this temporary variable
$cart[] = $data;
//Set back the data
$this->session->set_userdata('data', $cart);

//Later, when you want to iterate through the cart:
foreach ($this->session->userdata('data') as $item) {
    echo 'Id of product: ' . $item['product_id'] . "<br />";
    echo 'Quantity: ' . $item['quantity'] . "<br />";
    //and so on...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM