如果数组键之一与字符串中的值匹配,我将如何获得数组中的最大值。例如,将获得以下结果。
$decenders=array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$string='ABC'; //results as 0
$string='ABCg'; //results as 4
$string='ABCgj'; //results as 5
如果数组键之一与字符串中的值匹配,我将如何获得数组中的最大值。例如,将获得以下结果。
$decenders=array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$string='ABC'; //results as 0
$string='ABCg'; //results as 4
$string='ABCgj'; //results as 5
我认为最简单的方法(但不是最快的)是这样做:
$decenders= array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>9,'y'=>4);
$sData = 'ABqC';
arsort($decenders);
$rgResult = array_intersect(array_keys($decenders), str_split($sData));
$iResult = count($rgResult)?$decenders[array_shift($rgResult)]:0;
//var_dump($iResult); //9
这个怎么样:
function getScore($haystack, array $descenders) {
// the initial score is 0, which will be used if no $descenders match
$highest = 0;
foreach($descenders as $needle => $score) {
//if the descender exists in the string and has a higher score, update the score
if(strpos($haystack, $needle) !== false) {
if($score > $highest) {
$highest = $score;
}
}
}
return $highest;
}
$descenders = array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$tests = array('ABC', 'ABCg', 'ABCgj');
foreach($tests as $test) {
var_dump(getScore($test, $descenders));
}
输出:
int(0)
int(4)
int(5)
$decenders=array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$string1='ABC'; //results as 0
$string2='ABCg'; //results as 4
$string3='ABCgj'; //results as 5
function getResult($decenders, $string) {
$result = array_intersect_key(
$decenders,
array_flip(
str_split($string, 1)
)
);
return (count($result) > 0) ? max($result) : 0;
}
echo $string1, ' => ', getResult($decenders, $string1), PHP_EOL;
echo $string2, ' => ', getResult($decenders, $string2), PHP_EOL;
echo $string3, ' => ', getResult($decenders, $string3), PHP_EOL;
这会将字符串拆分为单个字符,遍历它们并为您提供最大的价值。
$result = 0;
foreach(str_split($string) as $char) {
if(array_key_exists($char, $decenders))
if($decenders[$char] > $result)
$result = $decenders[$char];
}
echo $result;