【问题标题】:how to sort Array based on another array values not keys?如何根据另一个数组值而不是键对数组进行排序?
【发布时间】:2022-01-12 15:34:39
【问题描述】:

我有这两个数组,我需要按 ID 排序第二个,就像第一个 ID 一样

如何根据第一个值重新排序第二个?我尝试了这个想法,但只适用于简单的数组: 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...

【问题讨论】:

    标签: php arrays wordpress sorting


    【解决方案1】:
    $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)
    );
    

    【讨论】:

      【解决方案2】:

      您可以从循环键数组开始,它最终将包含有序值。

      在键数组循环中,您为无序内容启动一个循环,检查有序键与无序键,如果它们相同,则将有序数组值设置为无序值。

      类似的东西。

      // $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;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-26
        • 2015-08-05
        • 2013-10-22
        • 2022-12-18
        • 1970-01-01
        • 2018-02-09
        • 1970-01-01
        相关资源
        最近更新 更多