문제

I need to find the worker with highest salary in PHP and display only him (his name, position and salary). Made several tries in the IF statement but none of them lead to what i needed.

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

This is my code and like that it will display all workers i have created but i need to output only the one with highest salary (worker 5 - Jim with 1000 salary)

도움이 되었습니까?

해결책

You can use this snippet:

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

Or this, as more clarity:

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

$max now contains a worker with maximum salary.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top