2014-05-13 11 views
0

我需要在PHP中找到工資最高的工作人員,並只顯示他(他的姓名,職位和薪水)。在IF聲明中做了幾次嘗試,但沒有一次導致我需要的東西。如何顯示在班級編輯的最大值數組

class Workers { 

    public $name; 
    public $position; 
    public $salary; 

    private function Workers($name, $position, $salary){ 
     $this->name = $name; 
     $this->position = $position; 
     $this->salary = $salary; 
    } 

    public function newWorker($name, $position, $salary){ 
//  if () { 
      return new Workers($name, $position, $salary); 
//  } 
//  else return NULL; 
    } 

} 

$arr = array(); 
$arr[] = Workers::newWorker("Peter", "work1", 600); 
$arr[] = Workers::newWorker("John", "work2", 700); 
$arr[] = Workers::newWorker("Hans", "work3", 550); 
$arr[] = Workers::newWorker("Maria", "work4", 900); 
$arr[] = Workers::newWorker("Jim", "work5", 1000); 

print_r($arr); 

這是我的代碼,並喜歡它會顯示我已經創建的所有工作人員,但我需要輸出只有一個最高工資(工人5吉姆 - 1000年薪)

回答

0

您可以使用此片段:

$max = null; 
foreach ($arr as $worker) { 
    $max = $max === null ? $worker : ($worker->salary > $max->salary ? $worker : $max); 
} 

或者這一點,因爲更加清晰:

$max = null; 
foreach ($arr as $worker) { 
    if (!$max) { 
    $max = $worker; 
    } elseif ($worker->salary > $max->salary) { 
     $max = $worker; 
    } 
} 

$現在最多包含3這是一名工資最高的工人。

+0

是的,它的工作,因爲我想。謝謝! :) – gxthegreat

相關問題