Olivertech
Olivertech

Reputation: 587

Multidimensional array in PHP 5

I have a simple question, but I can´t do this working.

I have this multidimensional array in my system:

array (size=5)
  'id_cli' => string '13' (length=2)
  'login_cli' => string 'userlogin' (length=10)
  'senha_cli' => string 'userpass' (length=3)
  'cli_nome' => string 'username' (length=16)
  'cart' => 
    array (size=3)
      'id' => int 48
      'tamanho' => string 'G' (length=1)
      'qtde' => int 1

This array is saved in my $_SESSION. The cart key is to save my cart products. In the above example, I have 1 product.

I need to save new products inside my session array cart, but I can´t do that. Every new product I try to insert, is saved over the first one, not inserted.

I am doing this:

But it is not working. What can I do to insert new arrays inside my $_SESSION['cart'] ?

And what I need to do to delete an specific product inside this $_SESSION['cart'] array ?

Thanks, Marcelo.

Upvotes: 0

Views: 56

Answers (2)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

You can use array_push($_SESSION['cart'], $newElement); to insert array element to existing array.

Alternate way of doing this is $_SESSION['cart'][] = $newElement;

To remove specific element you can use below logic

 $arrayKey=array_search($arrayKeyName,$_SESSION['cart']);
 if($arrayKey!==false) unset($_SESSION['cart'][$arrayKey]);

Alternate way of doing this

foreach($_SESSION['cart'] as $k => $v) {
  if($v == $arrayKeyName)
    unset($_SESSION['cart'][$k]);
}

Upvotes: 0

trex005
trex005

Reputation: 5115

You need to insert new products as an array OF an array. Try it like so :

$_SESSION['cart'][] = array("id" => $id_produto, "tamanho" => $tamanho_produto, "qtde" => 1);

Upvotes: 2

Related Questions