Php sort multidimensional array by another array

To sort a multidimensional array in PHP using another array as a reference, you can make use of the usort function along with a custom comparison function. This allows you to define your own sorting criteria.

Let’s assume you have a multidimensional array called $data that you want to sort based on the values in another array called $order. The $order array represents the desired order in which elements from $data should appear.

Example:

    $data = array(
      array('id' => 1, 'name' => 'John'),
      array('id' => 2, 'name' => 'Alice'),
      array('id' => 3, 'name' => 'Bob'),
      array('id' => 4, 'name' => 'David')
    );

    $order = array(2, 3, 1, 4);

    function compare($a, $b) {
      global $order;
      $pos_a = array_search($a['id'], $order);
      $pos_b = array_search($b['id'], $order);
      return $pos_a - $pos_b;
    }

    usort($data, 'compare');

    // Output the sorted array
    foreach($data as $item) {
      echo $item['name'] . '<br>';
    }
  

In this example, we have a multidimensional array $data with four elements, each containing an id and a name. We also have an array $order which holds the desired order based on the id values.

The compare function is used as the custom comparison function for the usort function. It takes two elements from the $data array and compares them based on their id values. The array_search function is used to find the position of each id in the $order array. The difference between these positions is then returned to determine the sorting order.

After calling the usort function, the $data array will be sorted according to the $order array. Finally, we can loop over the sorted array and output the names in the desired order.

The resulting output for the above example would be:

    Alice
    Bob
    John
    David
  

Leave a comment