在这种情况下如何转换成数组?

时间:2020-10-11 09:35:44

标签: laravel

在学生模型中,我已经设置了这样的属性

protected $appends = ['present'];

   public function getPresentAttribute(){
      return $this->getTotalDays()-$this->getAbsentDays();
   }

我的数据库看起来像这样

| id | student_name         |     created_at    |
*----*----------------------*-------------------*-- 
| 1  |  Adam                |     2020/11/10    | 
| 2  |  Annie               |     2020/11/10    |
|3   |  Paul                |     2020/11/10    |

如果我确实喜欢在控制器中这样做

  $students=Student::get();
  foreach($students as $stu){
   echo "<pre>"; print_4($stu->student_name,$stu->present); die;
  }

我的结果将是这样

 Adam -> 32
 Annie ->34
 Paul->33

但是我需要这样转换

 ['Students', 'Present Day',],
    ['Adam'     , 32],
    ['Annie'    , 34],
    ['Paul'     , 33],

所以在控制器中,我尝试这样

public function attendancePerformance(){
   $students=Student::get();
   $data=[];
   $student_data=[];
   $arrayHeader = ["Students","Present Day"];
   array_push($data,$arrayHeader);
       foreach ($students as $stu) {
            array_push($student_data, $stu->student_name,$stu->present);
         }
       array_push($data,$student_data)
    
   }
    

但是它不起作用。我应该怎么做?

0 个答案:

没有答案