2

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
        )

)
1
  • Use uksort, in your function check if either $a or $b is 'all', if so that's the "smaller" key, otherwise return $a - $b. Commented Mar 19, 2015 at 10:49

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

4 Comments

i already have seen usort, uasort but i couldnt figure out how can i make string key to show at top and numeric keys should come after the string key array..
Edited my post to add the comparison function.
i am using codeigniter MVC framework. i tried this in controller but still 'all' string key is showing at bottom of array.
I can't reproduce this behaviour. Are you sure your array isn't getting sorted after this ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.