array(4) {
[D.Fletcher] = array(22) {
[games] = int() 2
[ab] = int() 6
[runs] = int() 2
[hits] = int() 2
}
[A.Slegers] = array(22) {
[games] = int() 3
[ab] = int() 0
[runs] = int() 0
[hits] = int() 0
}
[A.Eaton] = array(22) {
[games] = int() 1
[ab] = int() 2
[runs] = int() 0
[hits] = int() 0
}
[S.Ohtani] = array(22) {
[games] = int() 3
[ab] = int() 6
[runs] = int() 2
[hits] = int() 3
}
I want to be able to sort the array starting at the third character of the key.
If I use ksort, I get:
A.Eaton
A.Slegers
D.Fletcher
S.Ohtani
But I want:
A.Eaton
D.Fletcher
S.Ohtani
A.Slegers
I can do this SQL as follows:
SELECT * FROM batters order by SUBSTRING(name, 3)
But I cannot figure out how to do it with a PHP sort.
I know I can get the keys with
$keys=array_keys($arr);
or in a loop:
foreach ($arr as $key => $value) {
echo $key;
}
Then possibly do a substr($key, 3) but I can’t figure out how to put it all together for a sort.
2
Answers
uksort example worked. Thank you.
FYI. I work on a platform that doesn't support code hinting for PHP 7, hence a code hint error using spaceship operator <=>. Using strcmp works as well too.
As I said in the comments
Output
test
Personally what I would do if I was you:
Would be to select the data with an extra field that you substr in SQL
Then instead of sorting in the DB, because of performance, you can now just use those as the keys for the data. If it’s possible it’s better to not do the substr in the sorting because this will be called many times. It’s very fast so it’s not a big deal. But I avoid using the
.
in array keys for other reasons. You may have duplicate names if you remove that so it’s hard for me to say.Basically I would build the data so I don’t need to do this, you can still sort in PHP.
It’s also possible to sort this as a multidimensional array by a specific key in each nested array for example you could include the name in the sub-array and make a search function to sort by that as well.. I would just try to avoid calling
substr
so much. Performance wise it’s probably not really a big deal, that’s just my instinct.