簡體   English   中英

如何根據另一個數組值而不是鍵對數組進行排序?

[英]how to sort Array based on another array values not keys?

我有這兩個 arrays,我需要按 ID 訂購第二個,就像第一個 ID 一樣

如何根據第一個值重新排序第二個? 我嘗試了這個想法,但僅適用於簡單的 arrays: https://develike.com/en/articles/sorting-an-array-by-values-based-on-another-array-in-php

有序 ID 數組:

Array
(
    [0] => 16351
    [1] => 18468
    [2] => 17160
    [3] => 1851
    [4] => 10734
    [5] => 18623
    [6] => 17813
    [7] => 14341
)

無序數組:

Array
(
    [0] => WP_Post Object
        (
            [ID] => 18623
            [post_author] => 57
         )
    [1] => WP_Post Object
        (
            [ID] => 18468
            [post_author] => 57
        )
      etc...
$arr = [ 16351, 18468, 17160, 1851, 10734, 18623, 17813, 14341 ];

class WP_Post {
  public $ID;
  public $post_author = 0;
  public function __construct($ID, $post_author = 0) {
    $this->ID = $ID;
    $this->post_author = $post_author;
  }
}

$arr2 = [
  new WP_Post(18623, 1),
  new WP_Post(18468, 2),
  new WP_Post(1851, 3),
  new WP_Post(14341, 4),
  new WP_Post(16351, 5),
  new WP_Post(17813, 6)
];

$result = array_filter(
  array_map(static fn($value) => array_values(
    array_filter($arr2, static fn($value2) => $value2->ID === $value)
  ), $arr)
);

您可以從循環鍵數組開始,它最終將包含有序值。

在鍵數組循環中,您為無序內容啟動一個循環,檢查有序鍵與無序鍵,如果它們相同,則將有序數組值設置為無序值。

像這樣的東西。

// $ordered_arr is the keys array
// $unordered_arr is the objects arrau

foreach ($ordered_arr as &$ordered_key) {
    foreach ($unordered_arr as $unordered_value) {
        // check if both unordered object id is equal to ordered key
        if ($unordered_value->ID == $ordered_key) {
            // set the object as value, we can do it this way because
            // $ordered_key is by referance
            $ordered_key = $unordered_value;
            break;
        }
    }
}

暫無
暫無

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

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