Tags
Asked 2 years ago
9 Jun 2021
Views 548
pratik

pratik posted

Sorting an array of arrays by custom order in php ?

how to Sorting an array of arrays by custom order in php ?
sachin

sachin
answered Apr 27 '23 00:00

To sort an array of arrays by custom order in PHP, you can use the usort () function and define a custom comparison function that compares the values based on your custom order.

Here's an example that demonstrates how to sort an array of arrays based on a custom order:



// The custom order we want to use
$customOrder = array('orange', 'apple', 'banana', 'pear');

// The array of arrays we want to sort
$myArray = array(
    array('name' => 'apple', 'color' => 'red'),
    array('name' => 'pear', 'color' => 'green'),
    array('name' => 'banana', 'color' => 'yellow'),
    array('name' => 'orange', 'color' => 'orange')
);

// Define the comparison function
function customSort($a, $b) {
    global $customOrder;
    $aIndex = array_search($a['name'], $customOrder);
    $bIndex = array_search($b['name'], $customOrder);
    return $aIndex - $bIndex;
}

// Sort the array using the custom order
usort($myArray, 'customSort');

// Print the sorted array
print_r($myArray);

In this example, we want to sort an array of arrays based on a custom order of fruit names. We define the custom order as an array, and then we define the array of arrays we want to sort.

Next, we define a comparison function called customSort() that takes two arrays as parameters and compares their name values based on their index in the customOrder array. The function uses the array_search() function to get the index of each fruit name in th e customOrder array, and then returns the difference between the two indexes.

Finally, we use the usort() function to sort the array of arrays based on the customSort () function, and then we print the sorted array using the print_r() function.

The output of the code will be:



Array
(
    [0] => Array
        (
            [name] => orange
            [color] => orange
        )

    [1] => Array
        (
            [name] => apple
            [color] => red
        )

    [2] => Array
        (
            [name] => banana
            [color] => yellow
        )

    [3] => Array
        (
            [name] => pear
            [color] => green
        )

)

As you can see, the array of arrays has been sorted based on the custom order of fruit names.
Post Answer