Php排序数组项问题

时间:2016-02-05 08:40:10

标签: php arrays

大家好,我有阵容季节和剧集名称 这是我的数组

- The Flash 2.Sezon 11.Bölüm
- The Flash 2.Sezon 1.Bölüm
- The Flash 1.Sezon 20.Bölüm
- The Flash 2.Sezon 3.Bölüm
- The Flash 3.Sezon 3.Bölüm

(sezon => season,bolum =>我的语言中的剧集)

我想将它们排在第一集到最后一集

- The Flash 1.Sezon 20.Bölüm
- The Flash 2.Sezon 1.Bölüm
- The Flash 2.Sezon 3.Bölüm
- The Flash 2.Sezon 11.Bölüm
- The Flash 3.Sezon 3.Bölüm

我尝试了asort功能但没有奏效。大多数商品的顺序正确,但其中一些没有。这是我的完整代码:

$args=array('post_type'  => 'bolum',
            'posts_per_page' =>-1,
            'orderby'    => 'title',
            'meta_query' => array(array(
                                    'key' => 'bolum_dizi',
                                    'value' => '"' . $post_id . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
                                    'compare' => 'LIKE'
                                        )
                                 )
            );
$episodes = get_posts($args);

这就是我订购和打印的方式

asort($episodes);
foreach( $episodes as $episode ){
echo $episode->post_title .'\n';}

我该怎么做? 非常感谢。

1 个答案:

答案 0 :(得分:2)

您正在寻找的是自然排序,可以使用natsort()功能实现:

<?php

$arr = array(
'- The Flash 2.Sezon 11.Bölüm',
'- The Flash 2.Sezon 1.Bölüm',
'- The Flash 1.Sezon 20.Bölüm',
'- The Flash 2.Sezon 3.Bölüm',
'- The Flash 3.Sezon 3.Bölüm',
);

natsort($arr);

echo '<pre>';
var_dump($arr);
echo '</pre>';

结果将是:

array(5) {
  [2]=>
  string(30) "- The Flash 1.Sezon 20.Bölüm"
  [1]=>
  string(29) "- The Flash 2.Sezon 1.Bölüm"
  [3]=>
  string(29) "- The Flash 2.Sezon 3.Bölüm"
  [0]=>
  string(30) "- The Flash 2.Sezon 11.Bölüm"
  [4]=>
  string(29) "- The Flash 3.Sezon 3.Bölüm"
}

对于一系列对象,您必须使用usortstrnatcmp

usort($episodes, function($a, $b) {
    return strnatcmp($a->post_title, $b->post_title);
});