简体   繁体   中英

PHP getting value from a multi dimensional array

I have a multi dimensional array that I am able to loop through with a FOR loop and return the values to enter into the database. The problem comes in when the user deletes an item which I then take out of the $_SESSION[cart] array using unset. Specifically if it was line 2 in the cart I would use

unset($_SESSION[cart][2]);

Now I can no longer use the FOR loop because the values I use in the FOR loop have gaps in them.

The original array would be:

$_SESSION['cart'][1] $_SESSION['cart'][2] $_SESSION['cart'][3]

AFTER deleting line 2 from the cart(it can be any line this is an example):

$_SESSION['cart'][1] $_SESSION['cart'][3]

This is how the array is structured:

$_SESSION['cart'][$lineId] = array('stockNumber' => $stockNumber, 'description' => $description, 'masterPrice' => $masterPrice);

$lineId is the line item in the cart

I currently retrieve the data from the cart using this loop:

for ($i = 1, $howMany = count($_SESSION['cart']); $i < $howMany+1; ) {
$stk_code = $_SESSION['cart'][$i]["stockNumber"];
$description = $_SESSION['cart'][$i]["description"]; 
$unitPrice = $_SESSION['cart'][$i]["masterPrice"];}

I need help in understanding this and a way to loop through the array regardless of line item number. I have no way of knowing how many items will be in the cart or how many they take out. Any help would be appreciated.

You can use foreach instead of for loop

$_SESSION['cart'][1] = array('stockNumber' => 1, 'description' => 'test', 'masterPrice' => 115);

    foreach ($_SESSION['cart'] as $value) {
      $stk_code = $value["stockNumber"];
      $description = $value["description"]; 
      $unitPrice = $value["masterPrice"];
    }

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