$aaray = [ 1=>[[7=>1, 8=2], [7=>2, 8=2]], 2=>[[7=>5, 8=2], [7=>3, 8=2]], ] $sorted = […
- User
$aaray = [ 1=>[[7=>1, 8=2], [7=>2, 8=2]], 2=>[[7=>5, 8=2], [7=>3, 8=2]], ]
$sorted = [ 1=>[[7=>1, 8=2], [7=>2, 8=2]], 2=>[[7=>3, 8=2], [7=>5, 8=2]], ]
php sort by key '7' value
- Assistant
To sort your multidimensional array by the value corresponding to key
'7'in each inner array in PHP, you can useusorton each sub-array.Here's a detailed example assuming your arrays have the structure you gave:
<?php $aaray = [ 1 => [[7 => 1, 8 => 2], [7 => 2, 8 => 2]], 2 => [[7 => 5, 8 => 2], [7 => 3, 8 => 2]], ]; // Loop through each sub-array and sort it by the value of key '7' foreach ($aaray as &$subArray) { usort($subArray, function($a, $b) { return $a[7] <=> $b[7]; // Comparison by key 7 }); } // After sorting print_r($aaray);Explanation:
- Use
foreachby reference (&$subArray) so modifications affect the original array. - Use
usortto sort each inner array. - The comparison function uses the spaceship operator () to sort numerically by the values of key .
- Use
- User
functional style
- Assistant
If you want a more functional style approach in PHP — meaning you avoid explicit mutation (
&references) and loops with sideeffects — you can usearray_maptogether with anonymous functions returning sorted sub-arrays.Example:
<?php $aaray = [ 1 => [[7 => 1, 8 => 2], [7 => 2, 8 => 2]], 2 => [[7 => 5, 8 => 2], [7 => 3, 8 => 2]], ]; $sorted = array_map(function($subArray) { // Copy subArray to avoid side effects $copy = $subArray; usort($copy, function($a, $b) { return $a[7] <=> $b[7]; }); return $copy; }, $aaray); print_r($sorted);Explanation:
array_mapapplies the sorting function to each sub-array.- Inside the callback, we copy
$subArrayand sort it withusort. - We return the sorted copy, this way
$aarayis not mutated. - Finally,
$sortedholds the new sorted array.
This fits a functional pattern: no mutation of the input, you treat data as immutable, return transformed data.
Output is exactly the same sorted array you want.
- User
php usort
- Assistant
Sure! Here's a simple example showing how to use
usortin PHP to sort an array of arrays by a specific key (in your case, key7):<?php $array = [ [7 => 5, 8 => 2], [7 => 3, 8 => 2], [7 => 10, 8 => 1], [7 => 1, 8 => 4], ]; // Sort the array by the value of key 7 usort($array, function ($a, $b) { return $a[7] <=> $b[7]; }); print_r($array);Explanation:
usort()sorts the array in place based on the user-defined comparison function.- The anonymous function compares the values under key
7using the spaceship operator<=>(introduced in PHP 7). - The sorting is ascending by default.
Output:
Array ( [0] => Array ( [7] => 1 [8] => 4 ) [1] => Array ( [7] => 3 [8] => 2 ) [2] => Array ( [7] => 5 [8] => 2 ) [3] => Array ( [7] => 10 [8] => 1 ) )