簡體   English   中英

按最高值對數組中的對象進行排序

[英]Sorting objects in array by highest value

我有一個foreach循環,可找到評論答復並將其存儲在$child_comments

<?php  echo '<pre>';
print_r($child_comments);
echo '</pre>'; ?>

我為每個父注釋得到一個單獨的數組:

Array
(
    [0] => stdClass Object
        (
            [comment_ID] => 603
            [comment_parent] => 600
            [user_id] => 2
        )

    [1] => stdClass Object
        (
            [comment_ID] => 601
            [comment_parent] => 600
            [user_id] => 2
        )

)

Array
(
     [0] => stdClass Object
        (
            [comment_ID] => 584
            [comment_parent] => 580
            [user_id] => 1
        )
)

Array
(
    [0] => stdClass Object
        (
            [comment_ID] => 608
            [comment_parent] => 520
            [user_id] => 2
        )

    [1] => stdClass Object
        (
            [comment_ID] => 598
            [comment_parent] => 520
            [user_id] => 2
        )

    [2] => stdClass Object
        (
            [comment_ID] => 521
            [comment_parent] => 520
            [user_id] => 2
        )

)

但是我需要按其評論ID(從最高ID到最低ID)對評論進行排序和輸出。

我可以得到我喜歡的評論

foreach ($child_comments as $objects) {
  echo $objects->comment_ID;
}

但它們仍將按照其父注釋進行排序。 有任何想法嗎? 理想的結構如下所示:

Array
(
    [0] => stdClass Object
        (
            [comment_ID] => 608
            [comment_parent] => 520
            [user_id] => 2
        )
    [1] => stdClass Object
        (
            [comment_ID] => 603
            [comment_parent] => 600
            [user_id] => 2
        )

    [2] => stdClass Object
        (
            [comment_ID] => 601
            [comment_parent] => 600
            [user_id] => 2
        )

    [3] => stdClass Object
        (
            [comment_ID] => 598
            [comment_parent] => 520
            [user_id] => 2
        )

    [4] => stdClass Object
        (
            [comment_ID] => 584
            [comment_parent] => 580
            [user_id] => 1
        )

    [5] => stdClass Object
        (
            [comment_ID] => 521
            [comment_parent] => 520
            [user_id] => 2
        )
)

如果您在不同的arrays獲得每個comments ,則可以先使用array_merge()創建單個數組,然后使用usort() sort最終數組進行sort例如,

<?php
    $comments=array_merge($child_comments);
    function cmp($a, $b) {
        return $b['comment_ID'] - $a['comment_ID'];//use $b->comment_ID if Object
    }
    usort($comments, "cmp");
    print_r($comments);
?>

如果您有復雜的排序標准,最好的方法是使用usort進行回調。

例如:

usort($arrayOfObjects, function($a, $b){
    if($a->comment_parent > $b->comment_parent) return 1;
    elseif($a->comment_parent < $b->comment_parent) return -1;
    else{
        // Do child compare here...
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM