Home >Backend Development >PHP Tutorial >How to Sort a Multidimensional PHP Array by an Inner Field\'s Value?

How to Sort a Multidimensional PHP Array by an Inner Field\'s Value?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 16:33:12609browse

How to Sort a Multidimensional PHP Array by an Inner Field's Value?

Sorting a Multidimensional Array by Inner Field in PHP

Suppose we have a multidimensional array resembling a database table, with each outer array element representing a row and each inner array containing field names and values. We want to sort the rows (outer array elements) by a specific field, such as "price."

To achieve this, we can utilize the following PHP function:

array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);

This line accomplishes our desired result in a concise manner. The array_multisort() function takes three arguments:

  1. array_column($yourArray, "price") - Extracts the "price" field values from each inner array into a one-dimensional array.
  2. SORT_ASC - Specifies that the "price" field should be sorted in ascending order.
  3. $yourArray - The multidimensional array to be sorted.

By chaining these functions together, we can effectively sort the outer array elements by the "price" field. It's important to note that this process overwrites the original $yourArray variable, so assigning the result to a different variable is advisable if the original order needs to be preserved.

Updates:

  • In recent PHP 7 versions, passing a variable by reference using "&" may cause errors. To resolve this, the following two-line workaround can be employed:
$col = array_column($yourArray, "price");
array_multisort($col, SORT_ASC, $yourArray);
  • PHP 8 eliminates this issue, allowing the one-line solution to be used without any adjustments.

The above is the detailed content of How to Sort a Multidimensional PHP Array by an Inner Field\'s Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn