【问题标题】:What is the best way to delete array item in PHP?在 PHP 中删除数组项的最佳方法是什么?
【发布时间】:2010-12-17 09:47:18
【问题描述】:

你能告诉我你从数组中删除一个项目的方法吗?你觉得好看吗?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    常用方式:

    根据manual

    unset($arr[5]); // This removes the element from the array
    

    过滤方式:

    还有array_filter() 函数来处理过滤数组

    $numeric_data = array_filter($data, "is_numeric");
    

    要获得顺序索引,您可以使用

    $numeric_data = array_values($numeric_data);
    

    参考文献
    PHP – Delete selected items from an array

    【讨论】:

      【解决方案2】:

      这取决于。如果要删除一个元素而不造成索引间隙,则需要使用array_splice:

      $a = array('a','b','c', 'd');
      array_splice($a, 2, 1);
      var_dump($a);
      

      输出:

      array(3) {
        [0]=>
        string(1) "a"
        [1]=>
        string(1) "b"
        [2]=>
        string(1) "d"
      }
      

      使用 unset 可以工作,但这会导致索引不连续。当您使用 count($a) - 1 作为上限的度量来迭代数组时,这有时会成为问题:

      $a = array('a','b','c', 'd');
      unset($a[2]);
      var_dump($a);
      

      输出:

      array(3) {
        [0]=>
        string(1) "a"
        [1]=>
        string(1) "b"
        [3]=>
        string(1) "d"
      }
      

      如你所见,count 现在是 3,但最后一个元素的索引也是 3。

      因此,我的建议是对具有数字索引的数组使用 array_splice,而仅对具有非数字索引的数组(实际上是字典)使用 unset。

      【讨论】:

      • 您也可以致电unset($a[2]); $a = array_values($a);
      【解决方案3】:

      这取决于:

      $a1 = array('a' => 1, 'b' => 2, 'c' => 3);
      unset($a1['b']);
      // array('a' => 1, 'c' => 3)
      
      $a2 = array(1, 2, 3);
      unset($a2[1]);
      // array(0 => 1, 2 => 3)
      // note the missing index 1
      
      // solution 1 for numeric arrays
      $a3 = array(1, 2, 3);
      array_splice($a3, 1, 1);
      // array(0 => 1, 1 => 3)
      // index is now continous
      
      // solution 2 for numeric arrays
      $a4 = array(1, 2, 3);
      unset($a4[1]);
      $a4 = array_values($a4);
      // array(0 => 1, 1 => 3)
      // index is now continous
      

      通常unset() 对于哈希表(字符串索引数组)是安全的,但如果您必须依赖连续数字索引,则必须使用array_splice()unset()array_values() 的组合。

      【讨论】:

      • 为什么你会使用 unset 和 array_values 而不是 array_splice?
      • @John:我能想到的一种情况是,当您想从一个数组中删除多个项目时。使用unset()-方式,您可以删除值而无需考虑更改键 - 如果您完成了通过array_values() 运行数组以标准化索引。这比多次使用array_splice() 更干净、更快捷。
      猜你喜欢
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      相关资源
      最近更新 更多