使用特定字段中的值排序数组

时间:2022-10-30 16:02:23

views.php

views.php

<?php
    $events = $events->as_array();
    asort($events);
    foreach($events as $event):   
        // some code comes here
    endforeach;
?>

Above code is used to sort the array in ascending order.I want to sort the array value in ascending order by referring the value in from_time colunm in database,that is the value should order in ascending order with respect to the value in from_time column.The above i tried is sorting the value with respect to id.How to sort it with respect to field(from_time) in database.

上面的代码用于按升序对数组进行排序。我想通过引用数据库中from_time colunm中的值按升序对数组值进行排序,即该值应按照from_time列中的值按升序排序。上面我尝试的是对id进行排序。如何根据数据库中的field(from_time)对其进行排序。

Update:

更新:

$events = $events->as_array();   

 function cmp(array $a, array $b) {
    if ($a['event_from_time'] < $b['event_from_time']) {//event_from_time is the db column name
        return -1;
    } else if ($a['event_from_time'] > $b['event_from_time']) {
        return 1;
    } else {
        return 0;
    }
}

 usort($events, 'cmp'); 

I am getting this error "ErrorException [ Recoverable Error ]: Argument 1 passed to cmp() must be an array, object given" in line "function cmp(array $a, array $b) {".

我收到此错误“ErrorException [Recoverable Error]:传递给cmp()的参数1必须是一个数组,对象给出”in the line“函数cmp(array $ a,array $ b){”。

Thanks

谢谢

1 个解决方案

#1


0  

<?php
    $events = $events->as_array();
    foreach($events as $event):
        $res_array[$event->mycat][] = $event->from_time;
    endforeach;
    ksort($res_array);
    print_r($res_array);
?>

#1


0  

<?php
    $events = $events->as_array();
    foreach($events as $event):
        $res_array[$event->mycat][] = $event->from_time;
    endforeach;
    ksort($res_array);
    print_r($res_array);
?>