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
Release: 2024-12-01 16:51:13
Original
120 people have browsed it

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

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!

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