首页 > 解决方案 > PHP 'FOREACH' 排序或过滤

问题描述

希望有人可以提供帮助,我有以下代码,并且想根据字段#_BOOKINGFORMCUSTOM{dbem_race_class} 进行排序,这可能吗?如果没有,有没有办法根据字段的内容过滤结果?

$people = array();
$EM_Bookings = $EM_Event->get_bookings();
if( count($EM_Bookings->bookings) > 0 ){
    ?>
    <ul class="event-attendees">
    <?php
           echo '<table style="width: 100%;"  cellpadding="25" border="1">
              <tr style="background-color:red; color:white"</tr>
                    <td style="vertical-align: top">Driver</td>
                    <td style="vertical-align: top">Race Type</td>
                    <td style="vertical-align: top">Car Manufacturer</td>
                    <td style="vertical-align: top">Car Model</td>
                    <td style="vertical-align: top">Engine Manufacturer</td>
                    <td style="vertical-align: top">PT Number</td>
             </tr>';
    $guest_bookings = get_option('dbem_bookings_registration_disable');
    $guest_booking_user = get_option('dbem_bookings_registration_user');
    foreach( $EM_Bookings as $EM_Booking){
        if($EM_Booking->booking_status == 1){
            $attendees_list = "";
            $attendees = $EM_Booking->booking_meta['attendees'];
            if ( !empty($attendees) ){
                foreach($attendees as $key => $value) {
                    $attendees_list = "<ul style='padding-left:50px'>";
                    foreach($value as $key_attendee => $value_attendee) {
                        $attendees_list .= "".$value_attendee["attendee_name"]."";
                    }
                    $attendees_list .= "</ul>";
                }
            }
            echo '<tr><td style="vertical-align: top">'. $EM_Booking->get_person()->get_name() .' </td><td style="vertical-align: top"> '. $EM_Booking->output("#_BOOKINGFORMCUSTOM{dbem_race_class}").' </td><td style="vertical-align: top">  '. $EM_Booking->output("#_BOOKINGFORMCUSTOM{dbem_car_manufacturer}").' </td><td style="vertical-align: top">  '. $EM_Booking->output("#_BOOKINGFORMCUSTOM{dbem_car_model}").' </td><td style="vertical-align: top">  '. $EM_Booking->output("#_BOOKINGFORMCUSTOM{dbem_engine_manufacturer}"). '</td><td style="vertical-align: top">  '. $EM_Booking->output("#_BOOKINGFORMCUSTOM{dbem_pt__number}").' </td></tr>'.$attendees_list.'</p>';
        }
    }
    echo '</table>';
    ?>
    </ul>
    <?php
}

标签: phparrayssortingfilterforeach

解决方案


您应该可以使用 usort https://www.php.net/manual/en/function.usort.php做一些事情

类似这样的东西:

usort($EM_Bookings, "booking_sorter");

function booking_sorter($a, $b)
{
    return strcmp($a->output("#_BOOKINGFORMCUSTOM{dbem_race_class}"), $b->output("#_BOOKINGFORMCUSTOM{dbem_race_class}"));
}

对于过滤,您可以使用 array_filter https://www.php.net/manual/en/function.array-filter.php执行基本相同的操作


推荐阅读