在会话变量中循环父数组

In testing code to learn how arrays work when stored to session variables I have made the following stored arrays:

$id=17; //product #17
$_SESSION['cart']['items'][$id]=array(
   'quantity'=>1,
   'SKUNumber'=>'GL335-a',
   'Name'=>'Widget',
   'UnitPrice'=>14.95
);
$id=25; 
$_SESSION['cart']['items'][$id]=array(
   'quantity'=>3,
   'SKUNumber'=>'GL398-c',
   'Name'=>'Mega-Widget',
   'UnitPrice'=>34.95
);
$id=19;
$_SESSION['cart']['items'][$id]=array(
   'quantity'=>1,
   'SKUNumber'=>'GL335-a',
   'Name'=>'Widget',
   'UnitPrice'=>14.95
);

I am confused on how to loop through the Key > Values at the ITEM level:

foreach($_SESSION['cart']['items'][25] as $key=>$value) // echo/loop all stored vaules in the item 25 array in session cart
    {
    // and print out the values
    echo $key." | ".$value."<br />";
    }

correctly produces 1 occurrence of the array stored in item 25:

  • quantity | 3
  • SKUNumber | GL398-c
  • Name | Mega-Widgets
  • UnitPrice | 34.95

But, when i remove the [25] from the code, i get: 17 | Array, 25 | Array, 13 | Array and a warning: "Notice: Array to string conversion in..."

What I want to produce is:

quantity: 1 | SKUNumber: GL335-a |Name: Widget |UnitPrice: 14.95

quantity: 3 | SKUNumber: GL398-c |Name: Mega-Widget |UnitPrice: 34.95

quantity: 1 | SKUNumber: GL378-b |Name: Super Widget |UnitPrice: 29.95

I'm obviously looping through the result set in a wrong way but not sure the correct way to loop through it to get the result I'm looking for. Thanks for any help.

<?php
    foreach($_SESSION['cart']['items'] as $arr)
    {
        echo "quantity: $arr['quantity'] | SKUNumber: $arr['SKUNumber']: GL378-b | Name: $arr['Name'] | UnitPrice: $arr['UnitPrice']";
    }

About Notice: Array to string conversion in, you're going to print out $value which is an array not a string so that's why you get that notice.

You should iterate over your array with another foreach loop or you can go with the my snippet.

try...

foreach($_SESSION['cart']['items'] as $id=>$arr) {
    foreach ($arr as $key => $value) {
        echo $key.":" .$value." | ";
    }
    echo "<br />";
}

OR

foreach($_SESSION['cart']['items'] as $id=>$arr) {
    echo "quantity: $arr['quantity'] | SKUNumber: $arr['SKUNumber'] | Name: $arr['Name'] | UnitPrice: $arr['UnitPrice'] <br />";
}

You're trying to serialize an Array by echoing the value, thats why you get the warning and the unexpected result. Try handling the $value as an array instead of just echoing it. Or looping inside the $value