简体   繁体   中英

PHP How to remove elements from an array and add to another array by key?

Not sure how to insert using foreach key deleted into new array

Function below

function array_delete_insert($delArrKey, $array1) {
//deletes from
    if(is_array($delArrKey)) {
        foreach ($delArrKey as $del_key => $del_value) {
            foreach ($array1 as $key => $value){
                if ($value == $del_value) {
                    unset($array1[$key]);
                }
            }
        }
    } else {
        foreach ($array1 as $key => $value){
            if ($value == $delArrKey) {
                unset($array1[$key]);
            }
        }
    }
    return array_values($array1);

// returns new array with all the deleted items
    $array2 = //all deleted elements array
    return array_values($array2);
}

//Calling the function by

$array1 = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$delArrKey = array('orange', 'apple');
$new_arr = array_delete_insert($delArrKey, $array1);

I might be misunderstanding the question but you could just array_push($newArray, $delItem) then return this.

For example:

$array1 = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$delArrKey = array('orange', 'apple');
$new_arr = array_delete_insert($delArrKey, $array1);

function array_delete_insert($delArrKey, $array1) {
  $array2 = [];
  //deletes from
      if(is_array($delArrKey)) {
          foreach ($delArrKey as $del_key => $del_value) {
              foreach ($array1 as $key => $value){
                  if ($value == $del_value) {
                      unset($array1[$key]);
                      array_push($array2, $value); //if item is deleted add to new array
                  }
              }
          }
      } else {
          foreach ($array1 as $key => $value){
              if ($value == $delArrKey) {
                  unset($array1[$key]);
              }
          }
      }
    return array_values($array1);
  }

Not sure if you wanted the new deleted items array, but you can just add that variable to the return.

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