我的切换案例允许查找具有两个特定值的表。 这就是我想做的事情:
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”
答案 0 :(得分:1)
首先要指出你的代码是你的关联数组的语法有错误。然后你可以使用我在下面显示的方式
<?php
$array = array (
"53" => "q",
"61" => "f",
"74" => "s",
"87" => "C",
"19" => "D",
"101" => "e",
"22" => "C",
"13" => "h");
foreach ($array as $key => $value) {
switch($value) {
case "C":
case "D":
case "e":
echo $key . ' ';
break;
}
}
结果:87 19 101 22
由于我的回答为您提供了另外的额外输出,因此您只能获取前三项,或者您可以编写重复过滤脚本,如Lionel Chan的回答所示。
答案 1 :(得分:1)
这是一个奇怪的逻辑,但这应该有效:
//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
)