开发者

Filtering an array in php, having both value- and key-related conditions

I'm trying to filter an array, in which the filter function is supposed to check for multiple conditions. For example, if element x starts with a capital letter, the filter function should return true. Except, if the element before element x satisfies certain other开发者_JAVA百科 conditions, then element x should not stay in the array and the filter function should therefore return false.

Problem is that the callback function in array_filter only passes the element's value and not its key... doing some magic with array_search will probably work, but I was just wondering whether I'm looking in the wrong place for this specific issue?


Sounds like a case for a good old foreach loop:

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


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

or

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


Did you use simple 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜