Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I sort a multidimensional array by one of the fields of the inner array in PHP?
In PHP, you can sort a multidimensional array by one of the fields of the inner arrays using the usort() function with a custom comparison function, or using array_multisort() for simpler cases.
Using usort() with Custom Comparison Function
The usort() function sorts an array using a user-defined comparison function. This method provides the most flexibility for complex sorting logic ?
<?php
function compare_array($var_1, $var_2) {
if ($var_1["price"] == $var_2["price"]) {
return 0;
}
return ($var_1["price"] < $var_2["price"]) ? -1 : 1;
}
$my_Array = array(
array("name" => "Product A", "price" => 25),
array("name" => "Product B", "price" => 15),
array("name" => "Product C", "price" => 35)
);
usort($my_Array, "compare_array");
foreach($my_Array as $item) {
echo $item["name"] . " - $" . $item["price"] . "<br>";
}
?>
Product B - $15 Product A - $25 Product C - $35
Using array_multisort()
For simpler sorting by a single field, array_multisort() provides a more direct approach ?
<?php
$products = array(
array("name" => "Product A", "price" => 25),
array("name" => "Product B", "price" => 15),
array("name" => "Product C", "price" => 35)
);
// Extract price column for sorting
$prices = array_column($products, 'price');
// Sort by price in ascending order
array_multisort($prices, SORT_ASC, $products);
foreach($products as $item) {
echo $item["name"] . " - $" . $item["price"] . "<br>";
}
?>
Product B - 15 Product A - 25 Product C - 35
Sorting in Descending Order
To sort in descending order, modify the comparison function or use SORT_DESC ?
<?php
$products = array(
array("name" => "Product A", "price" => 25),
array("name" => "Product B", "price" => 15),
array("name" => "Product C", "price" => 35)
);
$prices = array_column($products, 'price');
array_multisort($prices, SORT_DESC, $products);
foreach($products as $item) {
echo $item["name"] . " - $" . $item["price"] . "<br>";
}
?>
Product C - 35 Product A - 25 Product B - 15
Conclusion
Use usort() for complex sorting logic and array_multisort() with array_column() for simple field-based sorting. Both methods effectively sort multidimensional arrays by specific fields.
Advertisements
