更改多维数组中的元素位置

时间:2014-11-17 10:19:53

标签: php arrays multidimensional-array

我有一个像这样的多维数组:

Array
(
    [Members] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => John
                )

            [1] => Array
                (
                    [id] => 3
                    [name] => Mark
                )

            [2] => Array
                (
                    [id] => 4
                    [name] => Paul
                )

            [3] => Array
                (
                    [id] => 2
                    [name] => Robert
                )

        )

)

可以将name = Paul的位置更改为数组的顶部吗?

输出应为

Array
(
    [Members] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [name] => Paul
                )

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

            [2] => Array
                (
                    [id] => 3
                    [name] => Mark
                )

            [3] => Array
                (
                    [id] => 2
                    [name] => Robert
                )

        )

)

谢谢!

1 个答案:

答案 0 :(得分:2)

你可以先搜索保罗,然后为保罗创造一个临时保留者,在原始阵列中取消保罗,然后将保罗再次取消保存在其中,这样他就能登顶:

$array = [
    'Members' => [
        ['id' => 1, 'name' => 'John'],
        ['id' => 3, 'name' => 'Mark'],
        ['id' => 4, 'name' => 'Paul'],
        ['id' => 2, 'name' => 'Robert'],    
    ]
];

$name = 'Paul';
$temp = [];
foreach ($array['Members'] as $k => $value) {
    if($name == $value['name']) { // search for paul, if found
        $temp = $value; // put him inside temporarily
        unset($array['Members'][$k]); // remove paul
    }
}

array_unshift($array['Members'], $temp); // then put paul up top

echo '<pre>';
print_r($array);

Simple output