我需要在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 :(得分: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;
}
}
$ max现在包含一个薪水最高的工人。