更改数组元素的位置而不影响其结构

时间:2017-04-20 07:11:03

标签: php arrays codeigniter

我正在整合聊天页面。下方是聊天用户列表。但是用户可以通过两种方式访问​​聊天页面

1)http://domain/chat

一般来说,输出就像

Array
    (
        [0] => Array
            (
                [id] => 1
                [creater_id] => 6
                [receiver_id] => 7
            )

        [1] => Array
            (
                [id] => 3
                [creater_id] => 6
                [receiver_id] => 11
            )

        [2] => Array
            (
                [id] => 4
                [creater_id] => 6
                [receiver_id] => 13
            )

    )

2)http://domain/chat?receiver_id=11 在这种情况下,我希望输出像

Array
(
    [0] => Array
        (
            [id] => 3
            [creater_id] => 6
            [receiver_id] => 11
        )

    [1] => Array
        (
            [id] => 1
            [creater_id] => 6
            [receiver_id] => 7
        )

    [2] => Array
        (
            [id] => 4
            [creater_id] => 6
            [receiver_id] => 13
        )

)

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:1)

要排序的数组是$ arr,所需的第一个键是$ receiver_id

uksort($arr, function($a, $b) use($receiver_id, $arr) {
    if($arr[$a]["receiver_id"] == $receiver_id) {
        return -1;
    } elseif($arr[$b]["receiver_id"] == $receiver_id) { 
        return 1;
    } else {
        return $a < $b ? -1 : 1;
    }
});

答案 1 :(得分:0)

最佳做法是从MYSQL中进行排序,但您也可以尝试这样做。

$a = array(array('a' => 1, 'b' => 2), array('a' => 3, 'b' => 4), array('a' => 5, 'b' => 6), array('a' => 7, 'b' => 8)); 

$temp = array();

            foreach ($a as $key => $value)
            {
                if($value['b'] == 6)
                {
                    $temp[] = $a[$key];

                    unset($a[$key]);
                }
            }

     echo "<pre>";  
     print_r(array_merge($temp , $a)); exit;