0

Building a cart that stores the selected cart items in a session array until checkout. The array is stored as: $_SESSION ['cart'] ['items'] ['item number'] ... -> sub array fields like quantity, SKU etc. etc.

The output is as shown below, I am trying to figure out how to loop over all the sub arrays QUANTITY fields to get a total items in cart count. But since the 'item number' part of the array keys will change for each new/different product added to the cart, I cant figure out how to use a wildcard to represent that part of the KEY name in the foreach loop. Just to see any output I have tried:

foreach($_SESSION['cart']['items']['*']['quantity'] AS $key => $value) {echo $value;}

The array is stored/out put like this:

[cart] => Array
        (
            [items] => Array
                (
                    [RIF12345] => Array
                        (
                            [SKU] => RIF12345
                            [Brand] => Freemal
                            [Model] => AR3456BA
                            [Price] => 1230.55
                            [SalePrice] => 0.00
                            [Stock] => 12
                            [quantity] => 2
                        )

                    [11111111] => Array
                        (
                            [SKU] => 11111111
                            [Brand] => Marks
                            [Model] => 546454
                            [Price] => 6000.00
                            [SalePrice] => 4500.50
                            [Stock] => 15
                            [quantity] => 1
                        )

                )

        )

Am I approaching this loop from the wrong method? How do I write this foreach loop to accomplish what i am trying to do. Any help would be appreciated.

1 Answer 1

1

what about this:

foreach ($_SESSION['cart']['items'] as $ItemNumber => $Item)
 {$quantity+= $Item['quantity'];}
echo $quantity;
Sign up to request clarification or add additional context in comments.

2 Comments

Gives me error notices: Notice: Undefined variable: quantity in -- but it does output a proper total of 3 --- how can it output a correct total from $quantity but tell me it's undefined? is it because i dont declare it as NULL or something before the loop?
probably. try doing $quantity = 0 before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.