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
Release: 2024-12-18 16:33:12
Original
610 people have browsed it

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);
Copy after login

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);
Copy after login
  • 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template