Home > OS >  how to sort Array based on another array values not keys?
how to sort Array based on another array values not keys?

Time:12-08

I have this two arrays, and I need to order the 2nd one by ID, like the first one IDs

how can I re-order the second one based on the first one values? I try this idea but only works with simple arrays: https://develike.com/en/articles/sorting-an-array-by-values-based-on-another-array-in-php

Ordered ID Array:

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

Unordered Array:

Array
(
    [0] => WP_Post Object
        (
            [ID] => 18623
            [post_author] => 57
         )
    [1] => WP_Post Object
        (
            [ID] => 18468
            [post_author] => 57
        )
      etc...

CodePudding user response:

$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)
);

CodePudding user response:

You can start by looping the keys array, it will contain, in the end, the ordered values.

In the keys array loop you start a loop for the unordered content, check the ordered key against the unordered key, if they are the same, you set the ordered array value to be the unordered value.

Something like this.

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