PHP:关联数组交换使用第一个元素搜索值并对其余元素进行排序

时间:2014-07-11 08:23:39

标签: php arrays sorting

我收到以下数组(键是id元素的值)并需要对其进行排序,但实际上没有PHP排序功能可以帮助我。 在会话中,我得到一个等于其中一个id值的值。例如,我得到了值2.我必须交换数组,其id元素等于会话值(此处为:2)与数组的第一个元素。我想要排序的其他元素在我的主数组的键中升序。

继承阵列:

Array
(
[1] => Array
    (
        [id] => 1
        [name] => dummy11
    )

[2] => Array
    (
        [id] => 2
        [name] => dummy22
    )

[3] => Array
    (
        [id] => 3
        [name] => dummy33
    )

[4] => Array
    (
        [id] => 4
        [name] => dummy44
    )

[5] => Array
    (
        [id] => 5
        [name] => dummy55
    )

[6] => Array
    (
        [id] => 6
        [name] => dummy66
    )

[7] => Array
    (
        [id] => 7
        [name] => dummy77
    )

[8] => Array
    (
        [id] => 8
        [name] => dummy88
    )

[9] => Array
    (
        [id] => 9
        [name] => dummy99
    )

[10] => Array
    (
        [id] => 10
        [name] => dummy10
    )
)

我的问题是现在以这种方式排序,我收到以下数组:

Array
(
[2] => Array
    (
        [id] => 2
        [name] => dummy22
    )
[1] => Array
    (
        [id] => 1
        [name] => dummy11
    )

[3] => Array
    (
        [id] => 3
        [name] => dummy33
    )

[4] => Array
    (
        [id] => 4
        [name] => dummy44
    )

[5] => Array
    (
        [id] => 5
        [name] => dummy55
    )

[6] => Array
    (
        [id] => 6
        [name] => dummy66
    )

[7] => Array
    (
        [id] => 7
        [name] => dummy77
    )

[8] => Array
    (
        [id] => 8
        [name] => dummy88
    )

[9] => Array
    (
        [id] => 9
        [name] => dummy99
    )

[10] => Array
    (
        [id] => 10
        [name] => dummy10
    )
)

如果有人能帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用uksort()创建自定义排序(u用于用户定义,k是按键排序)。然后可以对此进行排序,但检查特殊值:

uksort($yourArray, function($a, $b){
    if($a == $SESSION['someId']){//Or '2' or whatever value you want to check.
        return -1;
    }elseif($b == $SESSION['someId']){
        return 1;
    }
    return $a - $b;
});

或者,您只需按键排序并使用this question的答案将商品移至顶部:

ksort($yourArray);
$key          = $SESSION['someId'];//Or '2' or whatever value you want to check.
$last_value   = array_pop($yourArray);
$yourArray    = array_merge(array($key => $last_value), $yourArray);