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

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

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂