Search code examples
phpsteamsteam-web-api

PHP, array - mixed order, steam api returns different order


how I can sort this by number, 0 - 1+ not by first letter?

error_reporting(E_ALL);
ini_set("display_errors", 1);

$players = array();             

$playerIds = [
    '76561197972192473',
    '76561198972352439',
    '76561198087304080',
    '76561198799985528',
    '76561198338485290'
];

$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=294CFDFSFCWE5EG5FE4&steamids=".implode(',', $playerIds);
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);

foreach ($json_decoded->response->players as $key=>$player) {

    $players[] = [
        'name' => $player->personaname,
        'profileurl' => $player->profileurl,
        'avatarfull' => $player->avatarfull,
        'personastate' => $player->personastate
    ];
} 

usort($players, function($a, $b) {
    if ($a['name'] === $b['name']) {
        return 0;
    }

    return ($a['name'] < $b['name']) ? -1 : 1;
});

When I remove usort, steam api will return ids everytime in different order, so can you help me how I can make it starts with 0 from playerIds.


Solution

  • Just add the steamid as the index and then sort it on keys:

    foreach ($json_decoded->response->players as $key=>$player) {
        $players[$player->steamid] = [
            'name' => $player->personaname,
            'profileurl' => $player->profileurl,
            'avatarfull' => $player->avatarfull,
            'personastate' => $player->personastate
        ];
    }
    ksort($players);
    

    Alternately, you could do it the way you're doing it but add the steamid to the $players array:

    $players[] = [
        'id' => $player->steamid,
        'name' => $player->personaname,
        'profileurl' => $player->profileurl,
        'avatarfull' => $player->avatarfull,
        'personastate' => $player->personastate
    ];
    

    Then sort on the id:

    array_multisort(array_column($players, 'id'), SORT_DESC, $players);
    

    There is maybe a parameter to be passed to the API that will return them sorted the way you want, not sure.