从包含数字php的变量中隔离字符串

时间:2014-11-04 12:12:16

标签: php variables switch-statement case

我正在尝试隔离我附加到仅包含数字的变量的文本。我查了一下,找不到任何有效的东西,或者甚至接近我正在尝试的东西。这就是我要找的东西:

$winning = max(array($var1."Var_One", $var2."Var_Two", $var3."Var_Tree", $var4."Var_Four"));
$winning = {the function that I'm missing}

我想找到伴随最高值变量的字符串,然后在开关案例中使用它,例如:

switch ($winning) {
    case "Var_One":
    echo "This variable is the highest value.";
    break;
    case "Var_Two":
    echo "This variable is the highest value.";
    break;
    case "Var_Three":
    echo "This variable is the highest value.";
    break;
    default:
    echo "Values are tied.";
}

我尝试过使用一个无法正常工作的正则表达式解决方案,并且strpos不能满足我的需求。

感谢任何帮助。

解答:

function getMaxValue(array $list) {
    $result = [];
    foreach($list as $k => $v) {
        if(!isset($result["value"]) || $result["value"] < $v) {
            $result = [
                "value" => $v,
                "key" => $k,
            ];
        }
    }
    return $result;
}
$winning = ["Var_One" => $var1, "Var_Two" => $var2, "Var_Three" => $var3];
$winning = getMaxValue($winning);
if(strpos($winning,'Var_One') !== false) {
    echo "Var_One is currently winning by ".$var1."!";
} else if(strpos($winning,'Var_Two') !== false) {
    echo "Var_Two is currently winning by ".$var2."!";
} else if(strpos($winning,'Var_Three') !== false) {
   echo "Var_Three is currently winning by ".$var3."!";
} else {
    echo "Tie.";
}

2 个答案:

答案 0 :(得分:0)

$winning = max(array_map("intval", array($var1."Var_One", $var2."Var_Two", $var3."Var_Tree", $var4."Var_Four")));

答案 1 :(得分:0)

我想你可能正在寻找这样的东西:

function getMaxValue(array $list)
{
    $result = [];
    foreach ($list as $k => $v) {
        if (!isset($result["value"]) || $result["value"] < $v) {
            $result = [
                "value" => $v,
                "key" => $k,
            ];
        }
    }
    return $result;
}

测试:

$list = ["one" => 2, "two" => 0, "three" => 5, "four" => 4];
var_dump(getMaxValue($list));

结果:

array(2) {
  ["value"]=>
  int(5)
  ["key"]=>
  string(5) "three"
}