"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort a Multidimensional PHP Array by a Sub-Value in Ascending Order?

How to Sort a Multidimensional PHP Array by a Sub-Value in Ascending Order?

Published on 2024-11-08
Browse:125

How to Sort a Multidimensional PHP Array by a Sub-Value in Ascending Order?

PHP: Sorting Multidimensional Array by a Sub-Value

This question seeks to sort a multidimensional PHP array based on the "mid" sub-value. To achieve this, the responder recommends employing the usort function, which allows for comparison-based sorting.

Here's how the code would look:

function cmp($a, $b) {
        return $a["mid"] - $b["mid"];
}
usort($arr, "cmp");

The cmp function compares the "mid" values of two array elements and returns -1, 0, or 1 based on the result. This ordering guides the sorting algorithm in usort to arrange the array in ascending order of "mid."

The end result is an array sorted by the "mid" values of its sub-values. Each key in the resulting array corresponds to a "mid" value, with the associated value being the corresponding sub-array.

Release Statement This article is reprinted at: 1729137554 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3