PHP:标记数组中项目的最佳方法是什么?

时间:2017-09-11 17:04:29

标签: php arrays regex

如果我希望通过手动标记数组中的某些条目(在必要时突出显示数据库中的特定条目),以便可以检测它们,从而区别对待它们。我想知道这样做的理想方法是什么?即最快(性能方面)和最有效。目前我这样做:

阵列:

"A"=>"yes",
"B"=>"no >",
"C"=>"why",

代码检测到它:

if (strpos($string,' >')!==false) {//action//}

因此,您可以看到它检测到我手动添加>的条目。但它也很烦人,因为这个角色必须用str_replace删除。

1 个答案:

答案 0 :(得分:0)

制作一系列答案。

问题:

$array = [
    "A" => "yes"
    "B" => "no" //this is the correct result.
    "C" => "why"
]

$answer = [
    0 => "B"; 
]

运行一些比较逻辑;数组的foreach值检查正确的答案:

foreach($array as $key => $value){
   if(in_array($key, $answer)){
       // this is the correct answer. So process.
       $correct = "The correct answer is ".$key." : '".$value."'"; 
   }
}
unset($key,$value);

 print $correct; // "The correct answer is B : 'no'"