1

假设我有四个值:

$right 
$down
$left
$up

我想从四个中选择最好的。这些值可以是false01-9D

False 是最差的,0 次之,1-9 明显不同,9 是最好的,最后 D 是最好的(双排)。

在 PHP 中检查这个的最好方法是什么?我正在考虑首先检查所有变量中的 D 。如果没有 D,则在所有四个中寻找最大的数字,然后寻找 0,最后寻找 false。

谢谢。

4

3 回答 3

2

在我看来,您似乎对 , 或 最后的结果感兴趣up,因此down将这些保留为数组中的值与它们的“强度”值配对并简单地对它们进行排序是有意义的。未经测试的粗略草稿:leftright

$values = array(
    array('type' => 'right', 'value' => false),
    array('type' => 'down',  'value' => 3)
    ...
);

usort($values, function ($a, $b) {
    static $order = array(false, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'D');

    $a = array_search($a['value'], $order, true);
    $b = array_search($b['value'], $order, true);
    return $a - $b;
});
于 2012-05-22T01:32:29.983 回答
0

这应该会给你你正在寻找的答案。

$test['up'] = false;
$test['down'] = 4;
$test['left'] = 'D';
$test['right'] = 0;

// for display only
print_r($test);

asort($test,SORT_STRING);

// for display only
print_r($test);

// Array key of the last value in array / best
echo array_pop(array_keys($test));
于 2012-05-22T01:46:48.583 回答
0

我首先将它转换为一个数组(你可以使用compact()它,或者只是存储在一个数组中),然后你可以使用uasort()用户定义的比较函数:

function myCompare($a, $b)
{
    // Convert false and D to -1 and 10, respectively.
    $a = ($a === false ? -1 : ($a == 'D' ? 10 : $a));
    $b = ($b === false ? -1 : ($b == 'D' ? 10 : $b));

    return ($b - $a);
}

$arr = compact('right', 'down', 'left', 'up');

uasort($arr, 'myCompare');

或者在 PHP 5.3+ 上,您可以使用闭包:

$arr = compact('right', 'down', 'left', 'up');

uasort($arr, function ($a, $b) {
    // Convert false and D to -1 and 10, respectively.
    $a = ($a === false ? -1 : ($a == 'D' ? 10 : $a));
    $b = ($b === false ? -1 : ($b == 'D' ? 10 : $b));

    return ($b - $a);
});
于 2012-05-22T01:39:43.017 回答