Search code examples
phpsortingmultidimensional-arrayassociative-arraysticky

Sort rows of a multidimensional array by column value with a sticky first row when a particular value is found


My multidimensional array is sorted alphabetically by the OwnerNickName field, but I need to make the OwnerNickName = 'My House' row as the sticky first row and then everything else sorted by OwnerNickname ascending.

Input:

[
    '0318B69D-5DEB-11DF-9D7E-0026B9481364' => [
        'OwnerNickName' => 'andy',
        'Rooms' => [ /* irrelevant */ ]
    ],
    '286C29DE-A9BE-102D-9C16-00163EEDFCFC' => [
        'OwnerNickName' => 'anton',
        'Rooms' => [ /* irrelevant */ ]
    ],
    '8BE18F84-AC22-102D-9C16-00163EEDFCFC' => [
        'OwnerNickName' => 'mike',
        'Rooms' => [ /* irrelevant */ ]
    ],
    '29B455DE-A9BC-102D-9C16-00163EEDFCFC' => [
        'OwnerNickName' => 'My House',
        'Rooms' => [ /* irrelevant */ ]
    ]
]

Solution

  • You may want to implement your own sorting function, e.g.:

    function cmp($a, $b)
    {
        if ($a['OwnerNickName'] == $b['OwnerNickName']) {
            return 0;
        }
        if ($a['OwnerNickName'] == 'My House') {
            return -1;
        } else if ($b['OwnerNickName'] == 'My House') {
            return 1;
        }
        return ($a['OwnerNickName'] < $b['OwnerNickName']) ? -1 : 1;
    }    
    usort($array, 'cmp');