在for循环内对自定义字段的值进行排序

时间:2018-10-18 00:24:32

标签: php wordpress sorting for-loop

我目前正在使用WordPress的Custom Field Suite插件来获取帖子类型之间的关系。我的代码如下:

<div class="productList">
    <?php 
    $values = CFS()->get( 'auctioned_items' ); 

    //pagination
    $nb_elem_per_page = 16;
    $page = isset($_GET['nav'])?intval($_GET['nav']-1):0;
    $current_page = $_GET['nav'];
    $data = $values;
    $count = 0;
    if($i %$nb_elem_per_page != 0) {
        $number_of_pages = intval(count($data)/$nb_elem_per_page)+2;
    } else {
        $number_of_pages = intval(count($data)/$nb_elem_per_page)+1;
    }

    foreach ( array_slice( $data, $page*$nb_elem_per_page, $nb_elem_per_page) as $post_id) {
        $lot_number = CFS()->get( 'lot_number', $post_id );
        $count++;
        if (empty($current_page)) {
            $newCount = ($count + ((1 + 1) - 1) * $nb_elem_per_page) - $nb_elem_per_page;
        } else {
            $newCount = ($count + (($current_page + 1) - 1) * $nb_elem_per_page) - $nb_elem_per_page;
        }
        //sort by $lot_number
    ?>
    <p class="lot"><?php echo $lot_number; ?></p>
    <h3><?php echo $the_post->post_title; ?></h3>
    <?php } ?>
</div>

$ values是一个列出相关帖子类型的所有ID的数组。看起来像这样 数组([0] => 111 [1] => 109 [2] => 110)

这将根据其在数组上的位置将其列出为相关帖子。但是,我想基于名为$ lot_number的自定义字段对值进行排序。 $ lot_number只是输入数字,但有时会涉及字母(例如8、9、10A,10B,11)

有没有办法做到这一点?由于涉及分页,因此令人困惑。

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,您可以尝试以下方法:

<div class="productList">
    <?php
    $values = CFS()->get( 'auctioned_items' );

    //pagination
    $nb_elem_per_page = 16;
    $page             = isset( $_GET[ 'nav' ] ) ? intval( $_GET[ 'nav' ] - 1 ) : 0;
    $current_page     = $_GET[ 'nav' ];
    $data             = $values;
    if ( $i % $nb_elem_per_page != 0 ) {
        $number_of_pages = intval( count( $data ) / $nb_elem_per_page ) + 2;
    } else {
        $number_of_pages = intval( count( $data ) / $nb_elem_per_page ) + 1;
    }

    $sorted = [];
    $posts  = array_slice( $data, $page * $nb_elem_per_page, $nb_elem_per_page );

    foreach ( $posts as $post_id ) {
        $sorted[ $post_id ] = CFS()->get( 'lot_number', $post_id );
    }

    // you can use either asort(low to high) or arsort(high to low)
    // there are some flags too, see here: http://php.net/manual/en/function.sort.php
    asort( $sorted );

    // and now...
    foreach ( $sorted as $post_id => $lot_number ) {
        ?>
        <p class="lot"><?php echo $lot_number; ?></p>
        <h3><?php echo $the_post->post_title; ?></h3>
    <?php } ?>
</div>