按时间排序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;
    }
    

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