简体   繁体   中英

How do I add multiple variables to an array without creating nested arrays

I have hit an issue that is surprisingly more difficult to solve than I thought it would be. And have not found an answer that gets me to the place I need to be. The goal is to add things to a list in a session variable that would work similar to a shopping cart. Essentially someone would add 1 item to the list, and then add additional items, and each would add to an array. But after using a variety of methods I still not getting what I need.

Here is the user story

  1. User clicks to add item to list
  2. Session Variable created - Item ID is added to session variable
  3. User adds additional item
  4. item added to session variable session is now an array
  5. Steps 3 and 4 repeated as many times as user requires.
  6. This all needs to go into a single flat array no nesting.

The code below seems to be the right solution. However it only returns the newest item ID and doesn't create the array. I have other solutions that create an array, but they create nested arrays for each additional item so, not what I need. Any help would be appreciated.

//Request Item From Post

$itemAdded = $_REQUEST['pPageItemID']; $currentItems = $_SESSION['ITEM_IDS'];

//If session is already set change it out into an array to add multiple IDs if (isset($_SESSION['ITEM_IDS'])) {

//Check to see if this is acutally a form post and then set session
if (isset($_REQUEST['pPageItemID'])){

    $newItems = array_merge($currentItems, $itemAdded);

    //Set new session with old and new IDs
    $_SESSION['ITEM_IDS'] = $newItems;
}

}

//Check if Session is Set if it is not create session var and add product ID if (is_null($_SESSION['ITEM_IDS'])) {

//Check to see if this is acutally a form post and then set session
if (isset($_REQUEST['pPageItemID'])){
    $_SESSION['ITEM_IDS'] = $itemAdded;
}

}

I figured this out. My problem was an assumption that PHP would understand a single variable as an array with a single variable. I was wrong!

A simple fix - I just needed to define it as an array during the merge. Updated the code to the below and it is working beautifully.

$newItems = array_merge((array)$currentItems, (array)$itemAdded);

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