douwu5009 2018-02-09 15:38
浏览 30
已采纳

按时间排序PHP

i have this function sort_by_time, the purpose of this function is to swap the time1 if the time2 is greater than time1 but my problem is im having an error of Undefined offset: 0. Sometimes the error is Undefined offset: 1. or Undefined offset: 2. Can someone help me to prevent this error in my code? I'm thinking this in these last 3 days but i can't think of any solution on this.

in this line the error occur.

      if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))

This error occurs because the $_time[0] is not set.

Sample time. This is dynamic not only limited to 3 sometimes it's 4, sometimes it's 5 or 1.

  • 1 => {#6356}
  • 2 => {#6352}
  • 3 => {#6257}

    Here's my full function code

    public static function sort_by_time($_time)
    {
        $count = 0;
    
    
        $n = count($_time);
        for ($i = 0; $i < $n-1; $i++)
        {
            for ($j = 0; $j < $n-$i-1; $j++)
            {
                if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))
                {
    
                    // swap temp and arr[i]
                    $temp = $_time[$j];
                    $_time[$j] = $_time[$j+1];
                    $_time[$j+1] = $temp;
    
                }
            }
        }
    
    
        return $_time;
    }
    
  • 写回答

1条回答 默认 最新

  • douzheng5717 2018-02-09 16:03
    关注

    Try this:

    public static function sort_by_time($_time)
    {
        usort($_time,function($ad,$bd)
        {
            $ad = Payroll2::convert_time_in_minutes($ad->time_in);
            $bd = Payroll2::convert_time_in_minutes($bd->time_in);
    
            if ($ad == $bd) {
               return 0;
            }
    
            return $ad < $bd ? -1 : 1;
        });
    
        return $_time;
    }
    

    if it doesn't work the problem can be in function Payroll2::convert_time_in_minutes

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog