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

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

问题描述:

I receive the following array (key is the value of the id element) and need to sort it, but actually no PHP sortfunction can help me here. I get, out of a session, a value which is equal to one of the id values. For example I get the Value 2. And I have to swap the array, which has the id element equals the session value (here: 2) with the first element of my array. The other elements I want to sort ascending in aspect to the key of my main array.

Heres the array:

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
    )
)

My Problem is now to sort it that way, that I receive the following array:

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
    )
)

If someone could help me I'd be grateful.

You can create a custom sort using uksort() (The u is for user defined, k is sort by key). This can then sort but check for special values:

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

Alternatively you can simply sort by key and use an answer from this question to move your item to the top:

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