In PHP, you can sort multidimensional arrays using the array_multisort()
function. Here’s an example of how to sort a multidimensional array in ascending order based on a specific column:
// Sample multidimensional array
$data = array(
array('id' => 1, 'name' => 'John', 'age' => 25),
array('id' => 2, 'name' => 'Mary', 'age' => 20),
array('id' => 3, 'name' => 'Peter', 'age' => 30)
);
// Sort the array in ascending order based on age
$age = array_column($data, 'age');
array_multisort($age, SORT_ASC, $data);
// Print the sorted array
print_r($data);
In this example, we first define a multidimensional array $data
with three columns: id
, name
, and age
. We then use the array_column()
function to extract the age
column from the array and store it in a separate array $age
. Finally, we use the array_multisort()
function to sort the original array $data
based on the values in $age
.
You can also sort the array in descending order by changing SORT_ASC
to SORT_DESC
. Additionally, you can sort the array based on multiple columns by passing multiple arrays to array_multisort()
.
You can sort a multidimensional array without using a built-in function like array_multisort()
, Just using a custom sorting function
// Sample multidimensional array
$data = array(
array('id' => 1, 'name' => 'John', 'age' => 25),
array('id' => 2, 'name' => 'Mary', 'age' => 20),
array('id' => 3, 'name' => 'Peter', 'age' => 30)
);
// Define a custom sorting function
function sortByAge($a, $b) {
return $a['age'] - $b['age'];
}
// Sort the array in ascending order based on age
usort($data, 'sortByAge');
// Print the sorted array
print_r($data);
Note: The original keys of the array will be lost after sorting. If you want to preserve the keys, use the uasort()
function instead of array_multisort()
.
My faamily members all the time say that I aam wasting
my time here at net, except I know I am getting familiarity everydcay by reading
such fastiidious articles.
Also visit mmy page; Vavadaonline.Mystrikingly.Com
Thanks