例如,如果我有:
$person1 = "10";
$person2 = "-";
$person3 = "5";
我需要确定编号最高的人,并在其字符串前加上“W”,并确定具有最低(数字)编号的人,并在他们的字符串前加上“L”
我想输出:
$person1 = "W10";
$person2 = "-";
$person3 = "L5";
答案 0 :(得分: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);
希望有所帮助。它应该为您提供有关使用哪些功能的提示。和平丹尼尔
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);
答案 1 :(得分: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];
然后可以使用$people_sorted['person1']
答案 2 :(得分: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"
}