Add data to array() in PHP

Asked

Viewed 793 times

0

I’m developing a PHP cart, however, when adding items to the array, I’m not getting it, I 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 each time I include a new item in the array, it replaces, and does not add. As I can just add items?

Note: I am using codeigniter to render.

  • Already tried to mount your array first and then insert it?

  • Not yet... ....

  • 1

    Do this, and use array_push instead of just = (this way you will recreate all the time the array)

  • Printa the amount of $i to make sure he’s changing

2 answers

4

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

2

Instead of recreating the array only use the array_push(), so you will be sure that new elements will be added.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.