簡體   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