如何从PHP中的特定值获取键?

玛丽

我的切换案例允许查找具有两个特定值的表。这是我想做的:

foreach ($array as $key => $value) {
   switch($value) {
             case "C": 
             case "D":
     //Take all key from "C" until I come across a second value "C" or "D"
   }
}

这是一个例子:

$array =
 (
      [53] => q
      [61] => f
      [74] => s
      [87] => C
      [19] => D
      [101] => e
      [22] => C
      [13] => h
 )

结果:“ 87 19 101”

陈狮(Lionel Chan)

这是一个奇怪的逻辑,但这应该可以工作:

//Triggers are the flags that trigger opening or close of filters
$triggers = array('C', 'D');
$filtered = [];
$stack = [];

foreach($array as $k => $v) {

    //If the trigger is opened and I see it again, break the loop
    if (in_array($v, $stack)) {
        break;
    }

    //If we sees the trigger OR the stack is not empty (we are opened)
    //continuously pull the keys out
    if (in_array($v, $triggers) || !empty($stack)) {
        $stack[] = $v;
        $filtered[] = $k;
    }
}

的输出是

Array
(
  [0] => 87
  [1] => 19
  [2] => 101
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章