0

更新:对不起,我想通了.. 我只取出 $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 个结果。可以启发我并告诉我我做错了什么吗?

如果有更好的方法,我也很想听听。

提前致谢!

4

2 回答 2

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...        
}
于 2012-11-28T13:26:57.153 回答
1

如果这些键始终存在,那么您实际上并不需要循环:

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

您可以添加检查是否已设置:

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

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

于 2012-11-28T13:27:45.787 回答