循环通过2d会话阵列购物车php

时间:2012-05-02 10:40:26

标签: php mysql multidimensional-array

我建立购物车并希望使用二维数组来存储商品ID和数量。当用户访问购物车时,我希望能够从数组中获取Items ID并从数据库中输出项目详细信息

/**************** 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/>';
        }

数组输出如此

ID:1 量:5

ID:2 量:1

我在确定如何分配ID和数量方面遇到了一些麻烦,以便我可以使用项目ID查询数据库。

1 个答案:

答案 0 :(得分:1)

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

或者您可以直接使用$value['id'] 这样的事情会帮助你..请尝试。 这是你需要的吗?