-1

So, I have this array of objects called $_SESSION['cart'], which gets data from front-end and store as an array of objects.

foreach($_SESSION['cart'] as $value){
$temp = (array) $value;
for($i = 0; $i < count($temp); $i++){
    echo $temp['name'] . "<< - name <br>";
    echo $temp['price'] . "<< - price<br>";
}
}

And since I want to convert each of the object into an array, I will loop through it and store a new array in $temp where each key and value will be outputted. I am amatuer and I have got pretty messed up in my head right now since I have been trying this for a couple of hours.

However, the output of the above code seems like

c1<< - name
1<< - price
c1<< - name
1<< - price
c1<< - name
1<< - price
c1<< - name
1<< - price
m1<< - name
1<< - price
m1<< - name
1<< - price
m1<< - name
1<< - price
m1<< - name
1<< - price 

which does not seem like a proper array for me. All the information I have is the name and I want to unset a sub-array that is related to that name. I only have two objects in it, but I have four keys in there and I think that's the reason why the output acts like there is 8 object.

So that is what I tried!

What I want to do is to unset an object related to a specific name.

$_SESSION['cart'] is an array, and everyitem within that is an object. If I loop and json_encode that $_SESSION['cart'], I would get a JSON in the console.

Kyi Zin
  • 823
  • 1
  • 6
  • 15
  • Does this answer your question? [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) – Sherif Mar 09 '20 at 02:57
  • Sadly, it does not, I do not want to convert an array to object, I want to convert an array of objects into an array of arrays. @Sherif – Kyi Zin Mar 09 '20 at 03:02
  • `$value` is coming through as a string in your example. Ensure that you have more than one `$_SESSION['cart']`, and maybe try `key => value`. – Obsidian Age Mar 09 '20 at 03:02
  • I can just foreach `$_SESSION['cart'] as value` and check if `$value->name` is equal to a `name`. However, the object inside the array will not be deleted with `unset($value)`. Is there a solution for this? – Kyi Zin Mar 09 '20 at 03:15

1 Answers1

-1

You can unset var in session this way:

foreach($_SESSION['cart'] as $key => $value){

   //The case when you need to unset the product
   if($value['product_name'] == 'Some Product'){
      unset($_SESSION['cart'][$key]);//unset the value of the cart from session , for specified product key
   }

}
Serghei Leonenco
  • 3,478
  • 2
  • 8
  • 16