簡體   English   中英

按另一個數組的值對StdClass對象數組進行排序

[英]Sorting an StdClass Object Array by the values of another array

我有一個StdClass數組。 每個對象都是這樣排序的(數組中大約有50個對象,但是我想我只想顯示一個結構):

stdClass Object (
    [display_name] => Bob Simons
    [post_title] => Lesson 1
    [meta_value] => 100
    [comment_approved] => passed
    [c_num2] => 26
    [term_id] => 3
)

我有另一個看起來像這樣的數組:

Array ( 
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 16 
    [4] => 17 
    [5] => 18 
    [6] => 19 
    [7] => 20 
    [8] => 21 
)

第二個數組基於[term_id]字段定義第一個的排序。 因此,基本上,具有[term_id] 3的所有內容都應位於數組的頂部,具有[term_id] 4的所有內容均應位於數組的頂部,所有這些均基於第二個數組。

我拼命地試圖找出方法,我一直在尋找usort之類的東西,但是全費了。

我希望有人能提供幫助,並會非常感謝。

嘗試這個

$sortedArray = [];
foreach ($order as $termId) {
    foreach ($objects as $object) {
        if ($object->term_id == $termId) {
            $sortedArray[] = $object;
        }
    }
}

$objects保存您的stdClass實例,並使用已排序的術語ID將您的列表$order

如果term_id應該始終以升序排序,則可以使用usort

usort($objects, function ($obj1, $obj2) {
    if ($obj1->term_id == $obj2->term_id) {
        return 0;
    }
    return ($obj1->term_id < $obj2->term_id) ? -1 : 1;
}); 

暫無
暫無

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

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