更新:抱歉,我想通了..我只取出$value[0],所以当然它只有一个结果。需要更多睡眠。多谢。我仍然愿意寻求更干净的方式来分割数组的建议。
我有一个具有以下结构的数组
$tdata
:
Array
(
[] => Array
(
[0] => Array
(
[firstName] => test
[lastName] => test
[userName] => [email protected]
[password] => test
[course] => test
[role] => test
)
[1] => Array
(
[firstName] => test
[lastName] => test
[userName] => [email protected]
[password] => test
[course] => test
[role] => test
)
)
[delete] => Array
(
[0] => Array
(
[firstName] => test
[lastName] => test
[userName] => [email protected]
[password] => test
[course] => test
[role] => test
)
)
[update] => Array
(
[0] => Array
(
[firstName] => test
[lastName] => test
[userName] => [email protected]
[password] => test
[course] => test
[role] => test
)
)
[outrole] => Array
(
[0] => Array
(
[firstName] => test
[lastName] => test
[userName] => [email protected]
[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 个结果。可以启发我并告诉我我做错了什么吗?
如果有更好的方法,我也很想听听。
如果这些键始终存在,那么你实际上不需要循环:
$create = $original['create'];
$outrole = $original['outrole'];
您可以添加检查是否已设置:
$create = isset($original['create']) ? $original['create'] : array();
如果不存在,这会将其设置为空白数组。
你的数组是嵌套的。要制作更小的数组,您应该在内部值内进行迭代:
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...
}