简体   繁体   中英

Updating a specific key within a multidimensional array (PHP)

I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;

.

The background

I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second). The button will just point back to this same page using the POST method.

The div on the right of the page will then load a "basket" which will use these post values and add them to an array.

When the "add" button is used again the value should update to +1 rather than create another sub_array.

.

What is currently happening

Currently when I click "add" the first time it adds the array as expected;

结果1

However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.

结果2

On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity

结果3

It just seems to be that second time I click "add".

.

The Script

<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

if (ISSET($_POST["prod"]))
{
    if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
    {
      $_SESSION["cart"][0] = 
      array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
    }
    else{
         echo 'running else';
         $_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

         if ($_POST['e']=='1')
         {
           $_SESSION['cart'] = '';
         }
        echo '<br /><br />';
print_r($_SESSION["cart"]);
}

Sample form

<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>

Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!

Many thanks to all in advance!

I tried to debug your code and a possible solution could be the following:

<?php

 session_start();

if(!isset($_SESSION["cart"]))
{
    $_SESSION["cart"]=[];
}

if (isset($_POST["prod"]))
{
    $prod_id=$_POST["prod"];
    //let suppose $_POST['prod'] is your item id
    $found=false;
    for($i=0;$i<count($_SESSION['cart']);$i++)
    {
        if(isset($_SESSION['cart'][$prod_id]))
        {
            echo "found! so add +1";
            $_SESSION['cart'][$prod_id][2]+=1;
            $found=true;
            break;
        }
    }
    if($found==false)
    {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
    }
}

         if (isset($_POST['e']) && $_POST['e']=='1')
         {
             $_SESSION['cart'] = '';
         }

        echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>

Another way to do it is using associative arrays. The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and an array with properties as name=>value for each item.

session_start();

if(!isset($_SESSION["cart"]))
{
    $_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
    $name=$_POST["name"];
    if(isset($_SESSION['cart'][$name]))
    {
        echo "found! so add +1";
        $_SESSION['cart'][$name]['quantity']+=1;
    }
    else
    {
       echo 'not found! so create a new item';
       $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
    }
}

         if (isset($_POST['e']) && $_POST['e']=='1')
         {
             $_SESSION['cart'] =[];
         }

        echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-OMIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>

It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:

$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);

For:

$_SESSION["cart"][0][2]+= 1;

By the way, try to properly indent your code when you are going to post it. It is hard to read.

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