2012-06-05 60 views
-4

例如,如果我有:確定變量具有最高值和最低值

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

我需要確定的最高數量的人,並用「W」前面加上他們的字符串,並確定與人最低的(數字)數量,並在前面加上他們的字符串以「L」

我試圖輸出:

$person1 = "W10"; 
$person2 = "-"; 
$person3 = "L5"; 
+0

'$ PERSON1 = 'W'。 $ PERSON1; $ person3 ='L'。 $ person3'? –

+0

^如果$ person3的人數超過$ person1,那麼這種方法無效。我需要*用PHP確定具有最高/最低編號的人。 – supercoolville

+0

你可以將數據格式化爲數組嗎?那麼它會超級簡單 – 2012-06-05 03:09:36

回答

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); 

希望有所幫助。它應該給你提示使用哪些函數。和平Danuel

解決方案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); 
+0

工作很愉快!非常感謝!!!!!!!! – supercoolville

+0

嘿,你可以追加它,但看到我的其他答案,以更好地實現你想要的迴應。 –

0

我會把每一個變量到一個數組,然後使用數組等等rt功能。

$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']

+0

我累了,但得到了一個錯誤「警告:不能使用標量值作爲數組」 – supercoolville

+0

查看原始版本 – supercoolville

+1

這是錯誤的。 arsort返回一個布爾值,所以它的返回值不能用於索引一個數組。更不用說'$ people'數組是聯想的而且沒有數字索引,因此你不能做'[0]'或'[2]'。 – nickb

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" 
} 
+0

這也適用!謝謝!! – supercoolville