Search code examples
phparraysjsonsteam-web-api

Sorting Arrays at the third Dimension


I try to sort this Array by the name but the function i wrote dont work

{
"response": {
    "game_count": 175,
    "games": [
        {
            "appid": 4000,
            "name": "Garry's Mod",
            "playtime_forever": 4040,
            "img_icon_url": "4a6f25cfa2426445d0d9d6e233408de4d371ce8b",
            "img_logo_url": "93c9364c3942223ab66195182fe1982af8a16584",
            "has_community_visible_stats": true
        },

Sorted by the name, which is at the third level

i tried:

function val_sort($array,$key) {

foreach($array as $k=>$v=>$g){
    $b[] = strtolower($v[$key]);
    }
SORT_ASC($b);
foreach($b as $k=>$g=>$v) {
    $c[] = $array[$k];
}

return $c;
}
$sorted = val_sort($array, 'name');

But this didnt work for me. I hope you can help me ^^


Solution

  • Use a foreach in combination with usort:

    foreach ($yourArray["response"] as $key => &$subarray) {
        usort($subarray, function($a, $b) {
        return $a['name'] <= $b['name'];
        });
    }
    print_r($yourArray); //now it's sorted