【问题标题】:How to find a value in an array and remove it by using PHP array functions?如何在数组中查找一个值并使用 PHP 数组函数将其删除?
【发布时间】:2011-03-04 19:35:07
【问题描述】:

如何查找一个值是否存在于数组中,然后将其删除?删除后我需要顺序索引顺序。

是否有任何 PHP 内置数组函数可以做到这一点?

【问题讨论】:

    标签: php arrays function built-in


    【解决方案1】:

    你需要先找到数组的键,这可以使用array_search()来完成

    完成后,使用unset()

    <?php
    $array = array( 'apple', 'orange', 'pear' );
    
    unset( $array[array_search( 'orange', $array )] );
    ?>
    

    【讨论】:

    • 这是结果 Array ( [0] => apple [1] => orange [2] => pear [3] => green ) 警告:C 中 array_search() 的参数计数错误:\wamp\www\test\test.php 第 5 行数组( [0] => apple [1] => orange [2] => pear [3] => green )
    • @learner de3.php.net/manual/en/function.array-search.php 中缺少 haystack 参数 - 手册是您的朋友。
    • 是的。这将起作用 $array = array('apple', 'orange', 'pear', 'green'); unset($array[array_search('orange', $array)]);但缺少数组序列。如何更正
    • 缺少序列是什么意思?它应该是什么顺序?
    • 数组索引为 0 2 3 4 现在缺少 1 我需要它,例如 0 1 2 4.. 等
    【解决方案2】:

    要在数组中搜索元素,可以使用array_search 函数,要从数组中删除元素,可以使用unset 函数。例如:

    <?php
    $hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
    
    print_r($hackers);
    
    // Search
    $pos = array_search('Linus Trovalds', $hackers);
    
    echo 'Linus Trovalds found at: ' . $pos;
    
    // Remove from array
    unset($hackers[$pos]);
    
    print_r($hackers);
    

    更多数组相关功能可以参考:https://www.php.net/manual/en/ref.array.php

    【讨论】:

    • 但是如果array_search因为没有找到而返回false,那么第一个数组值将被删除。
    • 如果没有完全匹配怎么办?如何执行通配符搜索?
    • 可以通过if(pos === false)测试是否匹配
    • 还要注意unset() 会将数组变成关联数组。要将其转回数组(没有键),请使用 array_values()
    • @mohitsoni 您好 mohitsoni,您是否考虑在执行unset 之前更新您的代码并检查条件if ($pos !== false)?原因是如果Linus Trovalds 不存在,您的代码将删除Alan Kay
    【解决方案3】:

    首先,正如其他人提到的,您将使用“array_search()”和“unset()”方法,如下所示:-

    <?php
    $arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
    unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
    print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
    ?>
    

    现在要重新索引同一个数组,而不对任何数组值进行排序,您将需要使用“array_values()”方法,如下所示:-

    <?php
    $arrayDummy = array_values( $arrayDummy );
    print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
    ?>
    

    希望对你有帮助。

    【讨论】:

    • 但是如果array_search因为没有找到而返回false,那么第一个数组值将被删除。
    • @algorhythm - 感谢您指出这一点!我会建议大家使用你提供的解决方案!
    • 当您知道某个答案有缺陷并且您无论如何都将 ot 留在页面上时,您只会通过错误的建议混淆他们和/或浪费他们的时间来损害研究人员的体验。
    【解决方案4】:

    以防万一您想使用任何提到的代码,请注意array_search 在“haystack”中找不到“needle”时返回 FALSE,因此这些示例将取消设置第一个(零索引)项目。改用这个:

    <?php
    $haystack = Array('one', 'two', 'three');
    if (($key = array_search('four', $haystack)) !== FALSE) {
      unset($haystack[$key]);
    }
    var_dump($haystack);
    

    上面的例子会输出:

    Array
    (
        [0] => one
        [1] => two
        [2] => three
    )
    

    这很好!

    【讨论】:

      【解决方案5】:
      <?php
      $my_array = array('sheldon', 'leonard', 'howard', 'penny');
      $to_remove = array('howard');
      $result = array_diff($my_array, $to_remove);
      ?>
      

      【讨论】:

      • 可以不循环删除多个值!
      • +1 避免了检查 array_search 的返回值的乏味
      • 似乎更高效,如果您使用通配符搜索删除元素,可以使用 array_search 或 preg_grep 函数创建数组 $to_remove。
      • 这个解决方案对我来说更干净。但是,请注意它保留索引,因此如果您想按数字顺序重新排列它们,您需要这样做:array_values(array_diff($my_array, $to_remove))
      • 这应该是正确的答案。如果未找到值,则数组保持不变。谢谢!
      【解决方案6】:

      要在数组中查找和删除多个值实例,我使用了以下代码

      $list = array(1,3,4,1,3,1,5,8);
      
      $new_arr=array();
      
      foreach($list as $value){
      
          if($value=='1')
          {
              continue;
          }
          else
          {
              $new_arr[]=$value;
          }     
      }
      
      
      print_r($new_arr);
      

      【讨论】:

      • 为什么要打扰continue 分支?为什么不直接推送!= '1'
      【解决方案7】:

      此解决方案是@Peter 删除多次出现的解决方案和@chyno 删除第一次出现的解决方案的组合。这就是我正在使用的。

      /**
       * @param array $haystack
       * @param mixed $value
       * @param bool $only_first
       * @return array
       */
      function array_remove_values(array $haystack, $needle = null, $only_first = false)
      {
          if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
          if (empty($haystack)) { return $haystack; }
      
          if ($only_first) { // remove the first found value
              if (($pos = array_search($needle, $haystack)) !== false) {
                  unset($haystack[$pos]);
              }
          } else { // remove all occurences of 'needle'
              $haystack = array_diff($haystack, array($needle));
          }
      
          return $haystack;
      }
      

      也可以看看这里:PHP array delete by value (not key)

      【讨论】:

        【解决方案8】:

        您可以使用array_filter 根据回调函数过滤掉数组的元素。回调函数将数组的每个元素作为参数,如果应该删除该元素,您只需返回 false。这还具有删除重复值的好处,因为它会扫描整个数组。

        你可以这样使用它:

        $myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
        $output = array_filter($myArray, function($value) { return $value !== 'banana'; });
        // content of $output after previous line:
        // $output = array('apple', 'orange', 'plum');
        

        如果你想重新索引数组,你可以像这样将结果传递给array_values

        $output = array_values($output);
        

        【讨论】:

          【解决方案9】:

          好的,这有点长,但做了一些很酷的事情。

          我试图过滤电子邮件列表,但排除某些域和电子邮件。

          下面的脚本将...

          1. 删除具有特定域的所有记录
          2. 删除任何具有确切值的电子邮件。

          首先您需要一个包含电子邮件列表的数组,然后您可以将某些域或个人电子邮件帐户添加到排除列表中。

          然后它会在最后输出一个干净的记录列表。

          //list of domains to exclude
          $excluded_domains = array(
              "domain1.com",
          );
          
          //list of emails to exclude
          $excluded_emails = array(
              "bob@domain2.com",
              "joe@domain3.com",    
          );
          
          function get_domain($email) {
          
              $domain = explode("@", $email);
              $domain = $domain[1];
              return $domain;
          
          }
          
          //loop through list of emails
          foreach($emails as $email) {
          
              //set false flag
              $exclude = false;
          
              //extract the domain from the email     
              $domain = get_domain($email);
          
              //check if the domain is in the exclude domains list
              if(in_array($domain, $excluded_domains)){
                  $exclude = true;
              }
          
              //check if the domain is in the exclude emails list
              if(in_array($email, $excluded_emails)){
                  $exclude = true;
              } 
          
              //if its not excluded add it to the final array
              if($exclude == false) {
                  $clean_email_list[] = $email;
              }
          
              $count = $count + 1;
          }
          
          print_r($clean_email_list);
          

          【讨论】:

          • 这个不同的任务看起来更适合array_diff()
          【解决方案10】:

          unset array_search 有一些非常可怕的副作用,因为它可能会意外地从数组中删除第一个元素,而不管值如何:

                  // bad side effects
                  $a = [0,1,2,3,4,5];
                  unset($a[array_search(3, $a)]);
                  unset($a[array_search(6, $a)]);
                  $this->log_json($a);
                  // result: [1,2,4,5]
                  // what? where is 0?
                  // it was removed because false is interpreted as 0
          
                  // goodness
                  $b = [0,1,2,3,4,5];
                  $b = array_diff($b, [3,6]);
                  $this->log_json($b);
                  // result: [0,1,2,4,5]
          

          如果您知道该值保证在数组中,那就去吧,但我认为array_diff 更安全。 (我用的是php7)

          【讨论】:

          • 仅当您不对false 进行严格比较时。多年前的算法和 chyno 的答案不会犯这个错误。
          【解决方案11】:
          $data_arr = array('hello', 'developer', 'laravel' );
          
          
          // We Have to remove Value "hello" from the array
          // Check if the value is exists in the array
          
          if (array_search('hello', $data_arr ) !== false) {
               
               $key = array_search('hello', $data_arr );
               
               unset( $data_arr[$key] );
          }
          
          
          
          # output:
          // It will Return unsorted Indexed array
          print( $data_arr )
          
          
          // To Sort Array index use this
          $data_arr = array_values( $data_arr );
          
          
          // Now the array key is sorted
          

          【讨论】:

            猜你喜欢
            • 2013-03-04
            • 2015-07-03
            • 2020-12-04
            • 1970-01-01
            • 2018-11-12
            • 2015-01-19
            • 1970-01-01
            • 2018-08-22
            • 1970-01-01
            相关资源
            最近更新 更多