I have this multidimensional array
[
"/api/dns" => [
0 => [
"method" => "GET",
"uri" => "foo0"
],
1 => [
"method" => "GET",
"uri" => "foo1"
],
2 => [
"method" => "GET",
"uri" => "foo2"
]
],
"/api/servers" => [
0 => [
"method" => "GET",
"uri" => "foo0"
],
1 => [
"method" => "GET",
"uri" => "foo1"
],
2 => [
"method" => "GET",
"uri" => "foo2"
]
]
];
I'm trying to sort by uri
.
I tried with usort
like this:
usort($myArray, function ($a, $b) {
return $a['uri'] - $b['uri'];
});
But this is not working because the sort is not done on right array so I got the error:
Undefined index: uri
I tried to add this function in a foreach without result. I don't know why this is not working because the sort is done on the right array.
foreach ($myArray as $key) {
usort($key, function ($a, $b) {
return $a['uri'] - $b['uri'];
});
}
Is this possible with usort
?
How can I sort by uri
with my usort
function?
As you loop through your first level, modify the subarrays "by reference" with the &
symbol.
Code: (Demo: https://3v4l.org/DthZW )
foreach($myArray as &$subarray){ // modify by reference
usort($subarray,function($a,$b){
return $a['uri']<=>$b['uri']; // use spaceship operator for ASC sorting
});
}
var_export($myArray);
If you don't want to use &
, then you can overwrite as you iterate.
foreach ($myArray as $key=>$subarray){
usort($subarray,function($a,$b){
return $a['uri']<=>$b['uri'];
});
$myArray[$key]=$subarray; // overwrite
}
Alternatively, you can combine array_multisort()
with array_column()
:
Code: ( Demo: https://3v4l.org/sOEqZ )
foreach($myArray as &$subarray){
array_multisort(array_column($subarray,'uri'),$subarray);
}
var_export($myArray);
And again, you can perform iterated overwrites with this as well.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments