Dave D
Dave D

Reputation: 938

Sorting A Multi Dimensional Array (Understanding Usort and MultiSort)

I have an array that is multiple database tables merged together into an array of the information that is needed. I want to sort this information alphabetically by name and then by id if it is the same name.

I viewed all of the following topics and was not able to produce a working result.

MY ARRAY as sudo dump

array(3){ 
    [0] => array(3){ 
        ['id'] => "1",  
        ['name'] => "Slippery Sasha", 
        ['type'] => "Electric Eel"
    }, 
    [1] => array(3){ 
        ['id'] => "2",  
        ['name'] => "Viscious Vipers", 
        ['type'] => "Snake"
    },
    [2] => array(3){ 
        ['id'] => "3",  
        ['name'] => "Finnic Fox", 
        ['type'] => "Rabid Fox"
    }, 
}

Code Attempt

// Sort
        $sortByTypes = array('name', 'id', 'type');
        usort($returnArray, function($a, $b) use($sortByTypes){
            foreach($sortByTypes as $field){
                $sort = strnatcasecmp($a[$field], $a[$field]);
                if($sort !== 0){
                    break;
                }
            }
            return $sort;
        });

MY INTENDED DUMP

  array(3){ 
        [0] => array(3){ 
            ['id'] => "3",  
            ['name'] => "Finnic Fox", 
            ['type'] => "Rabid Fox"
        }, 
        [1] => array(3){ 
            ['id'] => "1",  
            ['name'] => "Slippery Sasha", 
            ['type'] => "Electric Eel"
        }, 
        [2] => array(3){ 
            ['id'] => "2",  
            ['name'] => "Viscious Vipers", 
            ['type'] => "Snake"
        },

    }

BONUS IF you can explain how it works and what it is doing to sort the array giving me a better understanding of the feature that would be awesome!

Upvotes: 1

Views: 171

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use usort like as

usort($arr,function($a,$b){
    $c = strcasecmp($a['name'], $b['name']);
    $c .= $a['id'] - $b['id'];
    return $c;
});
print_r($arr);

Demo

Upvotes: 1

Related Questions