Tags
PHP , array
Asked 3 years ago
9 Jun 2021
Views 632
jignesh

jignesh posted

How do I Sort a Multidimensional Array in PHP ?

i have a Multidimensional Array like as blow :

<?php
$d= array(
"a","b"=>
	array("c","b",array("c","a")));
sort($d);
print_r($d);
?>


sort() function is not working to Sort a Multidimensional Array in PHP
rajiv

rajiv
answered Feb 27 '23 00:00

In PHP, you can use the array_multisort() function to sort a multidimensional array based on one or more columns. Here's an example of how to sort a multidimensional array by a specific column:


<?php

// Sample multidimensional array
$data = array(
    array('name' => 'John', 'age' => 32),
    array('name' => 'Jane', 'age' => 28),
    array('name' => 'Bob', 'age' => 42),
    array('name' => 'Alice', 'age' => 21)
);

// Sort the array by the 'age' column
$ages = array_column($data, 'age');
array_multisort($ages, SORT_ASC, $data);

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

?>


In this example, we first define a multidimensional array with two columns: name and age. We then use the array_column() function to extract the age column into a separate array, which we can then use as the first parameter to array_multisort(). The second parameter specifies the sort order (SORT_ASC for ascending order), and the third parameter is the original array that we want to sort.

The resulting sorted array will be:


Array
(
    [0] => Array
        (
            [name] => Alice
            [age] => 21
        )

    [1] => Array
        (
            [name] => Jane
            [age] => 28
        )

    [2] => Array
        (
            [name] => John
            [age] => 32
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 42
        )

)

This example sorts the array by a single column, but you can also sort by multiple columns by passing multiple arrays to array_multisort().
Post Answer