返回匹配数组键的最大值

时间:2013-09-11 13:35:28

标签: php

如果其中一个数组键与字符串中的值匹配,我将如何获得数组中的最大值。例如,将获得以下结果。

  $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

4 个答案:

答案 0 :(得分:2)

我认为最简单的方法(但不是最快)就是:

$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

答案 1 :(得分:1)

这会将字符串拆分为单个字符,迭代它们并为您提供最大的值。

$result = 0;
foreach(str_split($string) as $char) {
    if(array_key_exists($char, $decenders))
        if($decenders[$char] > $result)
            $result = $decenders[$char];
}
echo $result;

答案 2 :(得分:1)

这个怎么样:

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)

答案 3 :(得分:1)

$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;