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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 16:51:13119browse

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

Sorting a Multidimensional Array by an Inner Array Field in PHP

In PHP, you can manipulate multidimensional arrays to organize data based on specific criteria. Consider an array that represents a database table, where each element is a row and contains an inner array of field names and values.

To sort this array by the "price" field of the inner arrays, follow these steps:

  1. Extract the "price" Values: Use array_column function to extract the "price" field and store them in a separate array:

    $prices = array_column($yourArray, "price");
  2. Sort the "price" Array: Use sort() function (with PHP 7 or earlier) or sort() function (with PHP 8 and later) to sort the "price" array in ascending order:

    sort($prices); // For PHP 7 or earlier
    // OR
    $prices = sort($prices); // For PHP 8 and later
  3. Reorder the Outer Array: Use array_multisort() function to reorder the outer array based on the sorted "price" array. It takes a column array (prices), an order array (SORT_ASC), and the array to be sorted (yourArray):

    // For PHP 7 or earlier:
    array_multisort($prices, SORT_ASC, $yourArray);
    
    // For PHP 8 and later. No need for `$col` variable:
    array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);

By following these steps, you can efficiently sort a multidimensional array based on an inner array field in PHP, enabling you to organize data in a desired order.

The above is the detailed content of How to Sort a Multidimensional PHP Array by an Inner Array Field?. 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