简体   繁体   中英

Looping through a 2d session array shopping cart php

Im buliding a shopping cart and want to use a 2d array to store the items ID and quantity. When the user goes to the shopping cart I want to be able to grab the Items ID from the array and output the items details from the database

/**************** Adding to the 2d array ***********************/
    //Check to see if variable isset and then add item to shopping cart
    //$itemID is the ID of the product
    //$quantity is the quantity of the product they wish to order
    if(isset($_GET['add'])){
        $itemID = $_GET['add'];
        $quantity = $_POST['quantity'];
        $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
        header('xxx');//stops user contsanlty adding on refresh
    }

    /******************** Looping through the array  **********************/
        //need to loop through grab the item ID
        //then pull what we need from the database  

        //This is where I want to grab the id from the array and query the database

        $cart = $_SESSION['cart'];
        foreach ($cart as $value ){
        //works like it should
            foreach ( $value as $key=> $final_val ){
                echo $key;
                echo ':';
                echo $final_val;
                echo '<br/>';
            }
                echo '<br/>';
        }

The array outputs like so

id:1 quantity:5

id:2 quantity:1

Im having a little trouble figuring out how to seperate the ID and quantity so that I can query the database with the item ID.

foreach ( $value as $key=> $final_val ){
              if($key=='id')
              {
                echo $key;
                echo ':';
                echo $final_val;
                echo '<br/>';
              }
            }

or you can directly use like $value['id'] something like this will help you..please try. is this you need?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM