2016-01-20 3 views
0

Я работаю с WordPress тема, и есть содержание заполняется на одном из моих страниц массивом, «$chunks»мне нужно знать, как сортировать этот PHP массив по «POST_TITLE»

Вот как $chunks :

$chunks = array_chunk($args['exhibitors'], 5); 

Я пробовал сортировку с использованием следующего кода, но он не работает.

function sortByOrder($a, $b) { 
return $a['post_title'] - $b['post_title']; 
} 

usort($chunks, 'sortByOrder'); 

Я не думаю, что я понять, как получить доступ к строке в 'post_title'.

vardump из $chunks yeilds следующее (для первой записи в массиве, так что вы можете увидеть формат):

array(1) { 
    [0]=> array(5) { 
      [0]=> object(WP_Post)#538 (24) { 
       ["ID"]=>int(466) 
       ["post_author"]=> string(1) "1" 
       ["post_date"]=> string(19) "2016-01-20 20:46:50" 
       ["post_date_gmt"]=> string(19) "2016-01-20 20:46:50" 
       ["post_content"]=> string(866) "For more than three 
        decades, we have developed speakers and electronics to meet the demanding 
        requirements of professional applications. But we also create 
        technological advancements like Modeler® design software, the 
        Auditioner® audio demonstrator and LT loudspeaker technology. These 
        tools and innovations enable designers and consultants to create more 
        accurate, reliable, and cost-effective solutions. Bose® Professional 
        Systems is an entire division of engineers, trainers, technical 
        specialists and sales support teams. We provide support to a worldwide 
        network of dealers and installers. It includes product and technical 
        information, marketing and demonstration materials, design resources 
        and other materials and services. We help our dealers and installers 
        take projects from start to finish and provide a high level of service 
        after the job is done." 
        ["post_title"]=> string(4) "Bose" 
        ["post_excerpt"]=> string(0) "" 
        ["post_status"]=> string(7) "publish" 
        ["comment_status"]=> string(6) "closed" 
        ["ping_status"]=> string(6) "closed" 
        ["post_password"]=> string(0) "" 
        ["post_name"]=> string(4) "bose" 
        ["to_ping"]=> string(0) "" 
        ["pinged"]=> string(0) "" 
        ["post_modified"]=> string(19) "2016-01-20 20:46:57" 
        ["post_modified_gmt"]=> string(19) "2016-01-20 20:46:57" 
        ["post_content_filtered"]=> string(0) "" 
        ["post_parent"]=> int(0) 
        ["guid"]=> string(55) "XXXXX" 
        ["menu_order"]=> int(0) 
        ["post_type"]=> string(9) "exhibitor" 
        ["post_mime_type"]=> string(0) "" 
        ["comment_count"]=> string(1) "0" 
        ["filter"]=> string(3) "raw" 
      } 

ответ

1

Я думаю, вы должны были бы отсортировать массив перед тем комков его ,

$exhibitors = $args['exhibitors']; 
usort($exhibitors, function($a, $b) { 
    if ($a->post_title > $b->post_title) return 1; 
    if ($a->post_title < $b->post_title) return -1; 
    return 0; 
}); 

Затем вы можете ломоть отсортированный массив:

$chunks = array_chunk($exhibitors, 5); 

Если я ошибаюсь, о порядке сортировки/куске, эта функция сравнения должна работать.

Помните, что функция сравнения для usort должна возвращать целое число, отрицательное, положительное или нулевое, в зависимости от результата сравнения.

Вычитая один post_title от другого, как

return $a['post_title'] - $b['post_title']; 

, скорее всего, возвращение 0, потому что эти строки будут приводиться к номерам для вычитания, и, если они происходят, чтобы начать с числами, вы фактически будете получать

0 - 0 = 0 

так нет сортировки на всех, в основном

+0

Спасибо за ваш ответ. Я пробовал этот подход и получил следующую ошибку: Неустранимая ошибка: нельзя использовать объект типа WP_Post в качестве массива – user2977729

+0

@ user2977729 Я обновил ответ. Извините, я не заметил, что сначала был массив объектов. –

+0

Спасибо! Отлично. – user2977729

Смежные вопросы