简体   繁体   中英

editing a value in a multidimentional array in php

I've got a session called Cart_array which holds a multidimensional array in the following way:

$_SESSION['Cart_array'] = array(
                1 => array(
                    "ID" => $pid,
                    "QTY" => 1
                )
            );

this is how items are added to the cart session. pid is obtained from another form

if (isset($_POST['pid'])) {
        $pid    = $_POST['pid'];
        if (!isset($_SESSION['Cart_array']) || count($_SESSION['Cart_array']) < 1) { //check if cart session is not set or empty
            $_SESSION['Cart_array'] = array(
                1 => array(
                    "ID" => $pid,
                    "QTY" => 1
                )
            );
        } else {
                array_push($_SESSION['Cart_array'], array(
                    "ID" => $pid,
                    "QTY" => 1
                ));

        } //end else
    } //end if

the user has a form with the following things in a function:

     <?php foreach ($_SESSION['Cart_array'] as $eachItem) {
            $itemID = $eachItem['ID'];
            $itemQty = $eachItem['QTY']; >?

        <input class="qty" name="quantity" type="number" value="<?php echo $itemQty;?>" />
        <input type="submit" name="qtyChange<?php echo $itemID;?>" value="Change Qty" />
        <input name="qtyOfItem" type="hidden" value="<?php echo $itemID?>"/> 
}

This form will go through the Cart_array and display the quantity in the cart for every item. I want the user to be able to change the quantity in the cart for the specific item that they chose when they click the Change Qty button I'm not sure how to go around doing this?

You could edit the array like this

Your Array

$list = array([0]=>
                   array(
                         [ID]=>'XYZ' 
                         [QTY]=>'1'
                         )
             ); 


    my_function()
   {
    $list=$_SESSION['Cart_array']; 
    global $list;
    $list[0]['QTY'] = '2'; //or this 2 value can be taken from user using jquery 
    }

my_function();

For the script that this submits to, you want to loop through each item in the cart_array session and find it by that ID then change the quantity for that item.

 foreach($_SESSION['cart_array'] as $index => $item){
   if($item['ID'] == $_POST['ID']){
     $_SESSION['cart_array'][$index]['quantity'] = $_POST['quantity'];
  }
 }

Just pass your quantity value from the user like this

<?php
$_SESSION['Cart_array'] = array(
                1 => array(
                    "ID" => $pid,
                    "QTY" => 1
                )
            );

$_SESSION['Cart_array'][1]['QTY']=30;//Relaces the quantity from 1 to 30

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