Sizzling Code
Sizzling Code

Reputation: 6070

Sort array by both numeric and string keys

i have tried both ksort and asort but in both cases all always shows at bottom..

but i want to display array of index 'all' at top then numeric fields should be displayed.

Actually i am adding that key manually.

    $result['all'] = new stdClass();
    $result['all']->DisciplinaryAction = 'All';
    $result['all']->DisciplinaryActionID = 0;

i tried ksort($result) and also tried asort($result) but in both cases text/string always arranged to bottom..

Array
(
    [0] => stdClass Object
        (
            [DisciplinaryAction] => counseling
            [DisciplinaryActionID] => 1
        )

    [1] => stdClass Object
        (
            [DisciplinaryAction] => verbal warning
            [DisciplinaryActionID] => 2
        )

    [2] => stdClass Object
        (
            [DisciplinaryAction] => written warning
            [DisciplinaryActionID] => 3
        )

    [3] => stdClass Object
        (
            [DisciplinaryAction] => suspension
            [DisciplinaryActionID] => 4
        )

    [4] => stdClass Object
        (
            [DisciplinaryAction] => termination
            [DisciplinaryActionID] => 5
        )

    [all] => stdClass Object
        (
            [DisciplinaryAction] => All
            [DisciplinaryActionID] => 0
        )

)

Upvotes: 2

Views: 245

Answers (2)

FrancoisBaveye
FrancoisBaveye

Reputation: 1902

You can use uasort, uksort or usort to define how this should be handled.

http://php.net/manual/en/array.sorting.php

EDIT : Here's a comparison function for uksort

function cmp($a, $b)
{
    if ($a == $b)
        return 0;
    else if (is_string($a))
        return -1;
    else if (is_string($b))
        return 1;
    else
        return ($a < $b) ? -1 : 1;
}

Upvotes: 0

deceze
deceze

Reputation: 522015

See How can I sort arrays and data in PHP?.

The much more sensible way to do this, rather than sorting, is probably just to add the key to the beginning of the array directly:

$arr = array_merge(array('all' => new stdClass), $arr);

Upvotes: 2

Related Questions