将多维数组排序/拆分成许多较小的数组

时间:2012-11-28 13:16:19

标签: php arrays multidimensional-array

更新:抱歉,我想通了..我只取出了$ value [0],所以关闭导致它只有一个结果。需要更多的睡眠。非常感谢。我仍然愿意接受更清晰的分割阵列的建议。

我有一个具有这种结构的数组$tdata

Array
(
    [] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

        [1] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [delete] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [update] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [outrole] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

)

我正在尝试将其拆分为更小的数组。像这样:

foreach ($tdata as $key => $value) {

    if ($key == '') {
       $create[] = $value[0];
    }elseif ($key == 'outrole') {
       $outrole[]  = $value[0];
    }elseif ($key == 'delete') {
       $delete[] = $value[0];
    }elseif ($key == 'update') {
       $update[] = $value[0];
    }else{
     $noaction[] = $value[0];
    }

}

这种方式,我认为数组会自行覆盖。 print_r($create)或任何其他数组始终只返回1个结果。可以启发我,告诉我我做错了什么?

如果有更好的方法,我也很乐意听到。

提前致谢!

2 个答案:

答案 0 :(得分:1)

您的数组是嵌套的。要制作较小的数组,您应该在内部值内迭代:

foreach ($tdata as $key => $value) {
    if ($key == '') {
       foreach($value as $subValue) {
           $create[] = $subValue;
       }
    }elseif ($key == 'outrole') {
       foreach($value as $subValue) {
           $outrole[] = $subValue;
       }
    } // ... and so on...        
}

答案 1 :(得分:1)

如果这些键总是存在,那么你真的不需要循环:

$create = $original['create'];
$outrole = $original['outrole'];

您可以添加支票,如果已设置:

$create = isset($original['create']) ? $original['create'] : array();

如果它不存在,这将把它设置为空白数组。