-4

例如,如果我有:

$person1 = "10";
$person2 = "-";
$person3 = "5";

我需要确定数字最高的人并在他们的字符串前面加上“W”,还需要确定数字最低的人并在他们的字符串前面加上“L”

我正在尝试输出:

$person1 = "W10";
$person2 = "-";
$person3 = "L5";
4

3 回答 3

2
$persons = array(10, '-', '12', 34 ) ; //array of persons, you define this
$max_index = array_search($max = max($persons), $persons);
$min_index = array_search($min = min($persons), $persons);
$persons[$max_index] = 'W' . $persons[$max_index];
$persons[$min_index] = 'L' . $persons[$min_index];

print_r($persons);

希望有帮助。它应该为您提供有关使用哪些功能的提示。和平丹纽尔

解决方案 2

foreach((array)$persons as $index=>$value){
        if(!is_numeric($value))continue;
        if(!isset($max_value)){
                $max_value = $value;
                $max_index = $index;
        }
        if(!isset($min_value)){
                $min_value = $value;
                $min_index = $index;
        }
        if( $max_value < $value ){
                $max_value = $value;
                $max_index = $index;
        }
        if( $min_value > $value ){
                $min_value = $value;
                $min_index = $index;
        }
}

@$persons[$max_index] = 'W'.$persons[$max_index];//@suppress some errors just in case
@$persons[$min_index] = 'L'.$persons[$min_index];

print_r($persons);
于 2012-06-05T03:42:18.383 回答
0

我会将每个变量放入一个数组中,然后使用数组排序函数。

$people = array (
   'person1' => $person1,
   'person2' => $person2,
   'person3' => $person3
);

asort($people);

$f = key($people);

end($people);
$l = key($people);

$people[$f] = 'L' . $people[$f];
$people[$l] = 'W' . $people[$l];

然后可以通过使用来参考第 1 个人的分数$people_sorted['person1']

于 2012-06-05T03:12:17.967 回答
0

这是一个适用于任何人组合的有效解决方案:

$people = array (
   'person1' => 4,
   'person2' => 10,
   'person3' => 0
);

arsort( $people); // Sort the array in reverse order

$first = key( $people); // Get the first key in the array

end( $people);
$last = key( $people); // Get the last key in the array

$people[ $first ] = 'W' . $people[ $first ];
$people[ $last  ] = 'L' . $people[ $last ];

var_dump( $people);

输出:

array(3) {
 ["person2"]=>
  string(3) "W10"
  ["person1"]=>
  int(4)
  ["person3"]=>
  string(2) "L0"
}
于 2012-06-05T03:36:14.050 回答