PHP数组重新排列

时间:2013-07-20 02:13:22

标签: php arrays associative-array

我有一些问题需要在php中重新排列数组。这就是我所拥有的......

Array
(
    [N] => Array
        (
            [68] => sssssss ttttttt
            [69] => uuuuuu vvvvvvvv
        )

    [D] => Array
        (
            [05] => zzzzzzzz zzzzzzzz
            [07] => tttttttttttt ttttttttttt
        )

    [P] => Array
        (
            [88] => yyyyyyy zzzzzzzz
        )

    [C] => Array
        (
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz
        )

)

我想要的是以下......

Array
(
    [N] => Array
        (
            [68] => sssssss ttttttt
            [69] => uuuuuu vvvvvvvv
            // only C are added here with N
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz

        )

    [D] => Array
        (
            [05] => zzzzzzzz zzzzzzzz
            [07] => tttttttttttt ttttttttttt
        )

    [P] => Array
        (
            [88] => yyyyyyy zzzzzzzz
        )

    [C] => Array
        (
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz
        )
)

我需要将C元素添加到N中,而所有剩余的都保持不变,包括C本身。

我如何做到这一点?

有人帮忙请... 谢谢

3 个答案:

答案 0 :(得分:2)

相当简单的东西;只需将两个数组一起添加如下:

// add C to N
$arr['N'] += $arr['C'];

如果您不知道键名是什么,并且您只想定位第一个和最后一个项目:

reset($arr); $first = key($arr);
end($arr); $last = key($arr);

$arr[$first] += $arr[$last];

答案 1 :(得分:1)

这实际上非常简单。您需要做的就是遍历最后一个数组并将这些键值对添加到第一个数组中。 你走了:

    //---- $mainArray is your array.


foreach ($mainArray['C'] as $key => $value)
{
      $mainArray['N'][$key] = $value;
}

print_r($mainArray);

答案 2 :(得分:0)

试试这个:

$last_array = $main_array[count($main_array) - 1];
$new_array = array_merge($main_array[0], $last_array);
array_shift($main_array);
array_unshift($main_array, $new_array);
var_dump($main_array);