skip to Main Content
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


  1. Chosen as BEST ANSWER

    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.

    return strcmp( substr($a,2), substr($b,2) );
    

  2. As I said in the comments

    // Enter your code here, enjoy!
    $array = [
        "D.Fletcher" => [],
        "A.Slegers" => [],
        "A.Eaton" => []
    ];
    
    
    uksort($array, function($a,$b){
        return substr($a,2) <=> substr($b,2);
    });
    
    print_r($array);
    

    Output

    Array
    (
       [A.Eaton] => Array()
       [D.Fletcher] => Array()
       [A.Slegers] => Array()
    )
    

    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

    Select SUBSTRING(name, 2) as sort_name ....
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search