PHP:在 unset() 之后重新排列数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3753597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:59:05  来源:igfitidea点击:

PHP: Reorder arrays after unset()

phparrays

提问by Zebra

There are 2 functions involved.

涉及2个函数。

  1. Search array items for a given string
  2. unset() array item if string not found
  1. 搜索给定字符串的数组项
  2. 如果未找到字符串,则 unset() 数组项


$array = array("first", "second", "third", "fourth");

foreach($array as $i=> $string) {  
 if(stristr($string, "e")) {  
    unset($array[$i]);
 }   

}

secondis the array item with the character 'e'. If its unset, $array[1]would be left empty:

second是带有字符“e”的数组项。如果它的unset,$array[1]将留空:

$array[0] = "first"  
$array[1] = ""  
$array[2] = "third"  
$array[3] = "fourth"

I want $array[1]to be removed from the array (like in array_shift()), so that thirdtakes the place of secondand fourththe place of third:

我想$array[1]从数组中删除(如 in array_shift()),以便third代替secondfourth的位置third

$array[0] = "first"    
$array[1] = "third"  
$array[2] = "fourth"

回答by Matthew

$array = array_values($array);

回答by 538ROMEO

I think the best solution I've found is :

我认为我找到的最佳解决方案是:

Solution 1

解决方案1

if you just want to remove just one element :

如果您只想删除一个元素:

  array_splice($array,1,1); // all keys will be reindexed from 0

where the second and third parameters are offset (key) and length (how many to remove)

其中第二个和第三个参数是偏移量(键)和长度(要删除多少)

Solution 2

解决方案2

The best to remove multiple keys : use array_filter()to remove all empty strings and falsey value from the array then array_splice()to reorder :

最好删除多个键:用于array_filter()从数组中删除所有空字符串和 falsey 值,然后array_splice()重新排序:

array_splice(array_filter($array), 0, 0);