Thursday, 30 August 2018

PHP - Sorting an associative array by the values ​​from another array

I have two arrays, one is a multidimensional array which holds information, the other is a simple array which holds values for the order I want the first array in.

For example, I want my first array to be ordered by ID, by the values in the second array.
$users array:
array(3) {
    [0] => array(3) {
            'id' => 1,
            'name' => 'John Smith',
            'email' => 'john@example.com',
        },
    [2] => array(3) {
            'id' => 2,
            'name' => 'Jane Smith',
            'email' => 'jane@example.com',
        },
    [0] => array(3) {
            'id' => 3,
            'name' => 'Jack Smith',
            'email' => 'Jack@example.com',
        },
}

$order array:
array(3) {
    [0] => '2',
    [1] => '3',
    [2] => '1',
}

What I would like the outcome of the sorted array to be:
array(3) {
    [0] => array(3) {
            'id' => 2,
            'name' => 'Jane Smith',
            'email' => 'jane@example.com',
        },
    [2] => array(3) {
            'id' => 3,
            'name' => 'Jack Smith',
            'email' => 'jack@example.com',
        },
    [0] => array(3) {
            'id' => 1,
            'name' => 'John Smith',
            'email' => 'John@example.com',
        },
}

So as you can see, I would like the array keys to be reindexed, so they are always sequential starting from 0, but for the values of each element in the $users array to be re ordered.

I think that this should do the job:
$array = array(
    array(
            'id' => 2,
            'name' => 'Jane Smith',
            'email' => 'jane@example.com',
    ),
    array(
            'id' => 3,
            'name' => 'Jack Smith',
            'email' => 'Jack@example.com',
    ),
    array(
            'id' => 1,
            'name' => 'John Smith',
            'email' => 'john@example.com',
    ),
);

function cmp_by_optionNumber($a, $b) {
  return $a["id"] - $b["id"];
}
usort($array, "cmp_by_optionNumber");

var_dump($array);

It will sort your main array by the values of the "id" keys in the subarrays.

0 comments:

Post a Comment