0

我有一些问题要在 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 本身。

我该如何做到这一点?

有人帮忙请...谢谢

4

3 回答 3

2

很简单的东西;只需像这样将两个数组加在一起:

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

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

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

$arr[$first] += $arr[$last];
于 2013-07-20T03:57:14.693 回答
1

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

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


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

print_r($mainArray);
于 2013-07-20T03:53:09.487 回答
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);
于 2013-07-20T02:22:06.680 回答