Php 确定具有最高和最低值的变量
例如,如果我有:Php 确定具有最高和最低值的变量,php,Php,例如,如果我有: $person1 = "10"; $person2 = "-"; $person3 = "5"; 我需要确定数字最高的人,并在其字符串前加上“W”,还需要确定数字最低的人,并在其字符串前加上“L” 我试图输出: $person1 = "W10"; $person2 = "-"; $person3 = "L5"; 我将把每个变量放入一个数组中,然后使用数组排序函数 $people = array ( 'person1' => $person1, 'perso
$person1 = "10";
$person2 = "-";
$person3 = "5";
我需要确定数字最高的人,并在其字符串前加上“W”,还需要确定数字最低的人,并在其字符串前加上“L”
我试图输出:
$person1 = "W10";
$person2 = "-";
$person3 = "L5";
我将把每个变量放入一个数组中,然后使用数组排序函数
$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\u sorted['person1']
参考人员1的得分。这里有一个工作解决方案,可用于任何人员组合:
$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"
}
希望有帮助。它应该为您提供使用哪些函数的提示。和平达努尔
解决方案2
foreach((数组)$persons as$index=>$value){
如果(!是数值($value)),则继续;
如果(!isset($max_值)){
$max_value=$value;
$max_index=$index;
}
如果(!isset($min_值)){
$min_值=$value;
$min_index=$index;
}
如果($max_值<$value){
$max_value=$value;
$max_index=$index;
}
如果($min_值>$value){
$min_值=$value;
$min_index=$index;
}
}
@$persons[$max_index]=“W”。$persons[$max_index]//@抑制某些错误以防万一
@$persons[$min_index]=“L”。$persons[$min_index];
印刷(人);
$person1='W'$人1$person3='L'$person3
?^如果$person3的数字高于$person1,则此选项无效。我需要用PHP确定数字最高/最低的人。你能把数据格式化成数组吗?那么我能做的就是超级简单的眼睛……如果我把它放在一个数组中,解决方案会是什么?如果没有最高分数呢?它们是否都应加上WL
前缀?:)我对此感到厌倦,但出现了一个错误“警告:不能将标量值用作数组”,这是错误的。arsort返回一个布尔值,因此其返回值不能用于为数组编制索引。更不用说,$people
数组是关联的,并且没有数字索引,因此您无法执行[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);