【问题标题】:Sort Multi-dimensional Array by Value?按值对多维数组排序?
【发布时间】:2017-08-07 09:40:05
【问题描述】:

您好,我将尝试多排序数组,根据最近的帖子值显示数组列表,我需要订单列表请找到我的代码并帮助我们。

<?php
 $data = array();
    $i = 0;
    while($loop->have_posts()) : $loop->the_post();
    $title = get_the_title();
    $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'small');
    $comments_count = wp_count_comments(get_the_ID ());
    $comments_count = $comments_count->total_comments;

    ?>
        <div class="load_more" style="color:red;">
            <?php $row_id =  echo_views($id);
            $data[$i]['id'] = $row_id;
            $data[$i]['title'] = $title;
            $data[$i]['image'] = $large_image_url;
            $data[$i]['comments'] = $comments_count;            
            ?>
        </div>
    <?php    
    $i++;
    endwhile;
echo '<pre>';print_r($data);
?>

现在显示结果:

Array
(
    [0] => Array
        (
            [id] => 127
            [title] => test2
            [image] => Array
                (                    
                )
            [comments] => 0
        )

    [1] => Array
        (
            [id] => 116
            [title] => test3
            [image] => Array
                (                    
                )
            [comments] => 0
        )
    [2] => Array
        (
            [id] => 124
            [title] => test2
            [image] => Array
                (                    
                )
            [comments] => 0
        )

)

我需要结果(使用升序列表过滤 [id]):

Array
(
    [0] => Array
        (
            [id] => 127
            [title] => test2
            [image] => Array
                (                    
                )
            [comments] => 0
        )

    [1] => Array
        (
            [id] => 124
            [title] => test2
            [image] => Array
                (                    
                )
            [comments] => 0
        )

    [2] => Array
        (
            [id] => 116
            [title] => test3
            [image] => Array
                (                    
                )
            [comments] => 0
        )
)

【问题讨论】:

标签: php arrays wordpress sorting multidimensional-array


【解决方案1】:

使用 usort 对数组进行排序。您可以查看simple live demo here

usort($array, function($a, $b){return $b['id'] - $a['id'];});

【讨论】:

  • 在php7中可以使用宇宙飞船操作符
【解决方案2】:

使用 array_multisort 数组。

PHP reference

array_multisortarray_column 函数可用于使用键对多维数组进行排序,在您的示例中为 ID。array_column 函数用于指定键是用作排序顺序。

语法:

array_multisort(array_column(array_name,key_name),SORT_DESC/SORT_ASC,array_name);

解决方案:

array_multisort(array_column($data,'id'),SORT_ASC,$data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2017-01-26
    • 2021-10-02
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多