Add data in array () in PHP

0

I'm developing a cart in PHP, however, when adding items to the array, I'm not getting it, I've tried it as follows:

if($this->session->userdata('cart')==true){
    if(count($this->session->userdata('cart'))==0){
        $i = 0;
    } else {
        $i = count($this->session->userdata('cart'))+1;
    } 
    foreach($this->session->userdata('cart') as $value){
        $data[$i] = array(
            'cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
            'product_id' => $this->input->post('product_id'),
            'stock_purchase' => $this->input->post('stock_purchase'),
            'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
            'supplier' => $this->input->post('supplier'),
        );
        $i++;
    }
} else {
    $data[] = array(
        'cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
        'product_id' => $this->input->post('product_id'),
        'stock_purchase' => $this->input->post('stock_purchase'),
        'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
        'supplier' => $this->input->post('supplier'),
    );
}

The problem is that, every time I add a new item in the array, it replaces, and does not add. How can I just add items?

Note: I'm using codeigniter to render.

    
asked by anonymous 10.12.2018 / 20:14

2 answers

4

André, by what I understand you want to add elements to the end of the vector and the way you are doing you override the array. To add elements to the end of the vector there is the push .

    
10.12.2018 / 20:34
2

Instead of re-creating array just use array_push() , so you'll be sure to add new elements.

array_push($data, array('cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
                  'product_id' => $this->input->post('product_id'),
                  'stock_purchase' => $this->input->post('stock_purchase'),
                  'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
                  'supplier' => $this->input->post('supplier')));

Useful links: array_push

    
10.12.2018 / 20:47