Drenyl
Drenyl

Reputation: 934

Codeigniter - Unset session in a Two-dimensional array

I created two-dimensional array of session. Where a user can input an item and when he/she clicks the ADD button an array of that item will inserted in a session called item_names. Now I'm trying and cannot unset a certain item whenever a user clicks delete button which has it's unique id on it. I've found out that the function unset_userdata() don't support associative array already, as what I'm trying to achieve. Is there any functions aside from this?

Controller.php

public function delete_item(){
    $app_no = $this->input->post('app_no');  // product id of item
    $items_session = $this->session->userdata('item_names');

     foreach ($items_session as $key => $value) {
        if($value['product_id'] == $app_no){
            $this->session->unset_userdata($items_session[$key][$app_no]); 
        }
    }
  }

Array structure

Array
   (
       [0] => Array
     (
         [product_id] => 201708010010
         [product_name] => LADDER BRICK
         [total_prod_price] => P50
         [requestQty] => 1
     )
   (

Upvotes: 1

Views: 862

Answers (2)

Ashish Tiwari
Ashish Tiwari

Reputation: 2277

You cannot directly unset specific value of multidimensional array in session of codeingiter. You have to take all session value to variable. Unset the specific value and again set the variable in session as shown below:


    $items_session = $this->session->userdata('item_names');
    unset($items_session[$key][$app_no]);
    $this->session->set_userdata('item_names',$items_session);

Hope this will help.

Upvotes: 2

qwertzman
qwertzman

Reputation: 782

You will have to turn to regular PHP with unset.

public function delete_item(){
    $app_no = $this->input->post('app_no');  // product id of item
    $items_session = $this->session->userdata('item_names');

     foreach ($items_session as $key => $value) {
        if($value['product_id'] == $app_no){
            unset($items_session[$key][$app_no]); 
        }
    }
  }

Upvotes: 0

Related Questions