我有以下数组:
$original_array = [
[
"group" => "g1",
"department" => "d1",
"team" => null,
"data_col1" => "some_data1",
"data_col2" => "some_data2"
],
[
"group" => "g1",
"department" => "d1",
"team" => null,
"data_col1" => "some_data3",
"data_col2" => "some_data4"
],
[
"group" => "g1",
"department" => "d1",
"team" => "t3",
"data_col1" => "some_data5",
"data_col2" => "some_data6"
],
[
"group" => "g4",
"department" => "d6",
"team" => "t11",
"data_col1" => "some_data7",
"data_col2" => "some_data8"
]
];
我想将阵列"分组"到通用组/部门/团队中。
我尝试了以下方法:创建一个新数组,然后分配相关键(group/department/team),否则分配值:
$new_array = [];
foreach ($original_array as $row) {
foreach ($row as $key => $value) {
if ($key === "group" || $key === "department" || $key === "team") {
$new_array[$key] = $value;
} else {
$new_array[] = $value;
}
}
}
预期结果为:
[
0 => [
group => "g1",
department => "d1",
team => null,
data => [
0 => [data_col1 => "some_data1", data_col2 => "some_data2"],
1 => [data_col1 => "some_data3", data_col2 => "some_data4"]
],
1 => [
group => "g1",
department => "d1",
team => "t3",
data => [
0 => [data_col1 => "some_data5", data_col2 => "some_data6"]
],
2 => [
group => "g4",
department => "d6",
team => "t11",
data => [
0 => [data_col1 => "some_data7", data_col2 => "some_data8"]
]
]
但结果是:
[
"group" => "g4"
"department" => "d6"
"team" => "t11"
0 => "some_data1"
1 => "some_data2"
2 => "some_data3"
3 => "some_data4"
4 => "some_data5"
5 => "some_data6"
6 => "some_data7"
7 => "some_data8"
]
为什么?看起来它只给原始数组的最后一行赋值
1条答案
按热度按时间soat7uwm1#
这段代码应该会给予良好的结果:
这给予我: