Reputation: 1740
Supposed I have an array of
$arr = [
['Peter' => 4],
['Piper' => 4],
['picked' => 4],
['peck' => 4],
['pickled' => 4],
];
How can I sort this multidimensional array by key example (Peter). I tried using
ksort($arr);
but it just return a boolean
The output that I want
[
['peck' => 4],
['Peter' => 4],
['picked' => 4],
['pickled' => 4],
['Piper' => 4],
]
the array should be sorted by key and in ascending order regardless of letter case.
Upvotes: 0
Views: 78
Reputation: 47894
For less overheads while isolating and preparing data for comparison, pass the second level keys as the first parameter of array_multisort()
then set the necessary flags to compare the keys case-insensitively. Demo
array_multisort(
array_map(key(...), $array),
SORT_ASC,
SORT_STRING | SORT_FLAG_CASE,
$array
);
var_export($array);
Upvotes: 0
Reputation: 18557
You can do something like this,
$temp = array_map(function($a){
return key($a); // fetching all the keys
}, $arr);
natcasesort($temp); // sorting values case insensitive
$result = [];
// logic of sorting by other array
foreach($temp as $v){
foreach($arr as $v1){
if($v == key($v1)){
$result[] = $v1;
break;
}
}
}
Output
Array
(
[0] => Array
(
[peck] => 4
)
[1] => Array
(
[Peter] => 4
)
[2] => Array
(
[picked] => 4
)
[3] => Array
(
[pickled] => 4
)
[4] => Array
(
[Piper] => 4
)
)
Upvotes: 0
Reputation: 28529
Sort with usort like this, check the demo
usort($array,function($a,$b){
return strcmp(strtolower(key($a)),strtolower(key($b)));
});
Upvotes: 1
Reputation: 10739
The ksort()
method does an in-place sort. So while it only returns a boolean (as you correctly state), it mutates the values inside $arr
to be in the sorted order. Note that based on your expected output, it looks like you want to do a case insensitive search. For that, you need to use the SORT_FLAG_CASE
sort flag. So, instead of calling ksort($arr)
, you instead want to use ksort($arr, SORT_FLAG_CASE)
. You can see how ksort()
uses sort flags, in the sort()
method's documentation. Hope that helps!
Upvotes: 0