phparrayssortingmultidimensional-arraycustom-sort

Sorting array in PHP based on another array indexes


I have two arrays

// array of objects
$records = array(
  [0] => (object) [
             'id' => 1, //  (*)
             ....
        ],
  [1] => (object) [
            'id' => 2, //  (*)
             ....
        ],
   [2] => (object) [
            'id' => 3, //  (*)
             ....
        ],
);

// array 2
// the keys in this array refer to the object ids (*)
$sorted = array(
    '2'  => 7,
    '3'  => 4,
    '1'  => 2,
);

$new_records = array();

What I want to do is to sort the values of first array (i.e the objects) based on the order of the key index of the second array, so the end result in this case will become:

 $new_records = array(
      [0] => (object) [
                 'id' => 2,
                 ....
            ],
      [1] => (object) [
                'id' => 3,
                 ....
            ],
       [2] => (object) [
                'id' => 1,
                 ....
            ],
    );

$records = $new_records;

Solution

  • Try this

    $new_records = array();
    foreach( $sort as $id => $pos ) {
        foreach( $records as $record ) {
            if( $record[ 'id' ] == $id ) {
                $new_records[] = $record;
                break;
            }
        }
    }