Looping over a multidimensional array

<?php
$_SESSION["cart_item"] = array(
'cart_item' => array(
'id' => $id,
'product_name' => $product_name
));
}
$cart_items = $_SESSION["cart_item"];

foreach ($cart_items as $cart_item) {
echo $cart_item["id"] . $cart_item["product_name"];
}
?>

I have tried several variations of the foreach loop like the one above and I mostly get the error message: Notice: Array to string conversion. When I use:
var_dump($cart_items);

I get the following output:

array(1) { [“cart_item”]=> array(2) { [“id”]=> array(2) { [0]=> string(1) “2” [1]=> string(1) “3” } [“product_name”]=> array(2) { [0]=> string(19) “Adult Female Bike” [1]=> string(18) “Kids Unisex Bike” } } }

The solution can’t include nested foreach loops because I will be adding 3 more inner arrays to the multidimensional array and when I do this with nested foreach loops, I need 6 of them.

I retract my original question because I don’t need to make my multidimensional-array any larger after all. Please ignore my post.

If output a <pre> tag before the var_dump(), you will get formatted output -

array(1) {
	[“cart_item”]=> array(2) {
		[“id”]=> array(2) {
			[0]=> string(1) “2”
			[1]=> string(1) “3” }
		[“product_name”]=> array(2) {
			[0]=> string(19) “Adult Female Bike”
			[1]=> string(18) “Kids Unisex Bike” }
		}
	}

This session cart definition is missing a quantity value and by grouping the data as shown, overly difficult to access or loop over.

You were previously given a simple session cart definition. Why not use it and simplify all the code dealing with the cart?

A good data definition will help produce good code, since you won’t be performing unnecessary operations on the data every time you reference it.

Sponsor our Newsletter | Privacy Policy | Terms of Service