


How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?
Nov 29, 2024 am 06:14 AMSorting Multidimensional Arrays by Inner Array Field in PHP [duplicate]
Consider a multidimensional array representing a database-like structure, where each element denotes a row with inner arrays containing field name-value pairs. For instance:
Array ( [0] => Array ( [name] => 'Sony TV' [price] => 600.00 ) [1] => Array ( [name] => 'LG TV' [price] => 350.00 ) [2] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) }
The goal is to sort these rows based on the "price" field. The desired result is:
Array ( [0] => Array ( [name] => 'LG TV' [price] => 350.00 ) [1] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) [2] => Array ( [name] => 'Sony TV' [price] => 600.00 ) }
Solution:
To achieve this sorting, PHP offers the following simple solution:
array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);
Alternatively, the following snippet can be used to preserve outer array keys:
$col = array_column($yourArray, "price"); array_multisort($col, SORT_ASC, SORT_NUMERIC, $yourArray);
The above is the detailed content of How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
