检查数组中是否存在某个值,如果不存在则检查下一个值并确保不会出现先前的值

时间:2017-04-05 08:29:54

标签: php

好的,所以我有一个名为$ arraymaster的数组,它基本上是一个教育代码数组(从最高到最低):

$arrayedumaster=array("P H D", "Post Graduate", "Professional", "Graduate", "Technical", "ITI", "Under Graduate", "H S C Passed", "S S C Passed", "Upto Ninth", "Upto Fifth", "No Schooling");

现在有第二个数组列出了我从数据库中获得的个人资格:

$arrayedu=explode(',', $edudetail);

$ arrayedu的一些例子(个人可以有多个资格):

  • 研究生,HSC通过,研究生,专业,专业
  • 专业,SSC通过
  • 研究生,专业,技术

等。 现在我必须确定个人的最高资格(基于$ arraymaster)>>然后在$ arrayedu的基础上做一些动作。目前,我正在这么做:

 if(in_array("P H D", $arrayedu){
  $educode=1;
 }
 elseif(in_array("Post Graduate", $arrayedu) && !in_array("P H D",$arrayedu)){
 $educode=2;
}
 elseif(in_array("Professional", $arrayedu) && !in_array("P H D", $arrayedu) 
&& !in_array("Post Graduate", $arrayedu)){
 $educode=3;
}
elseif(in_array("Graduate", $arrayedu) && !in_array("Professional", 
$arrayedu) && !in_array("P H D", $arrayedu) && !in_array("Post Graduate", 
$arrayedu)){
$educode=4;
}

等等。所以基本上我试图从$ arrayedu获得最高资格,是否有一些更简单的方法来做到这一点?

3 个答案:

答案 0 :(得分:5)

使用array_intersectcurrent函数的解决方案:

$arrayedumaster = [
    "P H D", "Post Graduate", "Professional", "Graduate", "Technical", "ITI", "Under Graduate",
    "H S C Passed", "S S C Passed", "Upto Ninth", "Upto Fifth", "No Schooling"
];
$arrayedu = ["Graduate", "HSC Passed", "Graduate", "Professional", "Professional"];

$highest_edu = current(array_intersect($arrayedumaster, $arrayedu));
print_r($highest_edu);

输出:

Professional

答案 1 :(得分:0)

RomanPerekhrest已经提供了完美的单行答案,但也许这种方法可能具有灵感:

$arrayedumaster = [
  "P H D", "Post Graduate", "Professional", "Graduate", "Technical", "ITI",
  "Under Graduate", "H S C Passed", "S S C Passed", "Upto Ninth",
  "Upto Fifth", "No Schooling"
];
$arrayedu = [
  "Graduate", "HSC Passed", "Graduate", "Professional", "Professional"
];

$highestedu = count($arrayedumaster);
foreach ( $arrayedu as $value ) {
  if ( ($key = array_search($value, $arrayedumaster)) !== false ) {
    $highestedu = min($key, $highestedu);
  }
}

print_r($arrayedumaster[$highestedu]);

答案 2 :(得分:0)

请尝试以下排序:

$data = array(
    "Graduate", "H S C Passed", "Graduate", "Professional", "Professional"
);

$sortingArr = array("P H D", "Post Graduate", "Professional", "Graduate", "Technical", "ITI", "Under Graduate", "H S C Passed", "S S C Passed", "Upto Ninth", "Upto Fifth", "No Schooling", "ddd");

$result = array(); // result array
foreach($sortingArr as $val){ // loop
    $key = array_search($val, $data);
    if(in_array($val, $data)) {
        $result[$key] = $val; // adding values
    }

}
print_r($result); // print results