在PHP中使用array_splice/array_slice删除特定项

lov*_*ing 6 php arrays

如何在PHP中使用array_splice/ 删除特定项array_slice

例如:array('a','b','c'); 如何删除'b'?所以数组仍然是:array('a','c');

谢谢

小智 7

其实.我提出了两种方法来做到这一点.这取决于您将如何处理索引问题.

如果要在从数组中删除某些元素后保留索引,则需要unset().

<?php 
   $array = array("Tom","Jack","Rick","Alex"); //the original array

   /*Here, I am gonna delete "Rick" only but remain the indices for the rest */
   unset($array[2]);
   print_r($array);
?>  
Run Code Online (Sandbox Code Playgroud)

输出将是:

Array ( [0] => Tom [1] => Jack [3] => Alex )  //The indices do not change!
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要一个新数组而不保留以前的索引,那么使用array_splice():

<?php 
  $array = array("Tom","Jack","Rick","Alex"); //the original array
  /*Here,we delete "Rick" but change indices at the same time*/
  array_splice($array,2,1);  // use array_splice()

  print_r($array);
?>
Run Code Online (Sandbox Code Playgroud)

这次的输出是:

Array ( [0] => Tom [1] => Jack [2] => Alex ) 
Run Code Online (Sandbox Code Playgroud)

希望,这会有所帮助!


Ali*_*xel 5

如何删除“蓝色”?

干得好:

$input = array("red", "green", "blue", "yellow");
array_splice($input, array_search('blue', $input), 1);
Run Code Online (Sandbox Code Playgroud)


Pek*_*ica 4

基本上:就去做吧。

手册有很好的例子,如下所示:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
Run Code Online (Sandbox Code Playgroud)

如果某些事情不适合您,请为您的问题添加更多详细信息。

  • @lovespring 抱歉,我没明白。这就是第三个参数“$length”的用途。`array_splice($input, 2, 1)` 应该可以解决问题。此类内容最常见于手册中,请务必先查看手册页。 (2认同)