Monday, 27 August 2018

Access a multidimensional array (stored in $ _SESSION) using foreach. give a warning

I have a multidimensional array $_SESSION("cart"), when I print it recursively, it gives:
array

[0] => Array
    (
        [type] => Side orders
        [name] => French Fries
        [choice] => small
        [quantity] => 1
        [price] => 225
    )

[1] => Array
    (
        [type] => Specialty Pizzas
        [name] => Vegetarian
        [choice] => large
        [quantity] => 1
        [price] => 1580
    )

[2] => Array
    (
        [type] => Specialty Pizzas
        [name] => Mediterranean
        [choice] => large
        [quantity] => 1
        [price] => 1580
    )

) I am trying to print the cart by looping through the array of arrays (keys:1,2,3...) and have direct access to [type, name, choice...] however when I try to access it using the following code:
if (isset($_SESSION["cart"]) && count($_SESSION["cart"])>0)
{
            echo '<pre>';
            print_r ($_SESSION["cart"]);
            echo '</pre>';
            foreach ($_SESSION["cart"] as $key->$item){

                $ty = $item->type;
                $nm = $item->name;
                $ch = $item->choice;
                $pr = $item->price;
                $qt = $item->quantity;
                ?>  

                <li>

                    <?= $ty ?>
                    <?= $nm ?>
                    <?= $ch ?>
                    <?= $pr ?>
                    <?= $qt ?>

}}

this gives a warning and fatal error: Warning: Attempt to assign property of non-object in ... on line 15 (the line that contains foreach loop)
Warning: Creating default object from empty value in ... line 14 Fatal error: Cannot access empty property in ...on line 14
I tried to set key=0 before the loop and increment it in the loop; and iterate the key but it didnt seem like a valid solution because it was not printing the values, but the fatal error was gone. I am not sure what is wrong.
me error reporting is
error_reporting(E_ERROR | E_WARNING | E_PARSE);

Change the code in:
foreach ($_SESSION["cart"] as $key->$item) {

to:
foreach ($_SESSION["cart"] as $key => $item) {

The foreach statement have two structures:
1. foreach ($array as $value)
2. foreach ($array as $key => $value)

0 comments:

Post a Comment