【问题标题】:Filtering an array in php, having both value- and key-related conditions过滤 php 中的数组,同时具有值​​和键相关条件
【发布时间】:2011-08-31 05:38:39
【问题描述】:

我正在尝试过滤一个数组,其中过滤器函数应该检查多个条件。例如,如果元素 x 以大写字母开头,则过滤器函数应返回 true。除非,如果元素 before 元素 x 满足某些其他条件,则元素 x 应该留在数组中,因此过滤器函数应该返回 false。

问题是 array_filter 中的回调函数只传递元素的值而不是它的键......用 array_search 做一些魔术可能会起作用,但我只是想知道我是否在寻找错误的地方来解决这个特定问题?

【问题讨论】:

  • 尝试遍历for 中的数组 :)

标签: php array-filter


【解决方案1】:

你用过简单的foreach吗?

$prev;
$first = true;
$result = array();
foreach ($array as $key => $value)
{
    if ($first)
    {
        $first = false;

        // Check first letter. If successful, add it to $result

        $prev = $value;
        continue; // with this we are ignoring the code below and starting next loop.
    }

    // check $prev's first letter. if successful, use continue; to start next loop.
    // the below code will be ignored.

    // check first letter... if successful, add it to $result
}

【讨论】:

    【解决方案2】:

    听起来像是一个很好的老式 foreach 循环的例子:

    foreach ($arr as $k => $v) {
      // filter
      if (!$valid)
        unset($arr[$k]);
    }
    

    【讨论】:

      【解决方案3】:
      $newArray=array();
      foreach($oldArray as $key=>$value){
         if(stuff){
            $newArray[$key]=$value;
         }
      }
      

      foreach($array as $key=>$value){
         if(stuff){
            unset($array[$key]);
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-03-12
        • 2022-01-07
        • 1970-01-01
        • 2015-01-04
        • 2023-04-03
        • 1970-01-01
        • 2018-06-30
        • 2021-07-02
        • 2022-01-18
        相关资源
        最近更新 更多