通过数字和字符串键对数组进行排序

时间:2015-03-19 10:39:52

标签: php arrays

我已经尝试了ksort和asort,但在这两种情况下都显示在底部..

但我希望显示索引数组' all'在顶部,然后应显示数字字段。

实际上我是手动添加该密钥。

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

我尝试ksort($result)并尝试了asort($result),但在这两种情况下,文字/字符串始终排列在底部..

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
        )

)

2 个答案:

答案 0 :(得分:2)

请参阅How can I sort arrays and data in PHP?

更明智的做法,而不是排序,可能只是直接将键添加到数组的开头:

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

答案 1 :(得分:0)

您可以使用uasortuksortusort来定义如何处理此问题。

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

编辑:这是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;
}