在对数据进行分组之后是否可以删除密钥?现在,我正在使用csv文件导入功能。我有两行数据,同一学生但书不同,因为我想根据学生ID对书进行分组。
代码
foreach ($book as $item) {
$item['books'] = [
'number' => $item['number'],
'description' => $item['description'],
];
if (!isset($group_by[$item['student_id']])) {
$group_by[$item['student_id']] = array(
'student_id' => $item['student_id'],
'name' => $item['name'],
);
}
$group_by[$item['student_id']]['books'][] = $item['books'];
}
这是我的分组功能,可以按预期工作,但数据结构与我的系统不匹配
结果在这里
array:1 [
"ST001" => array:9 [
"student_id" => "ST001"
"name" => "joe"
"books" => array:2 [
0 => array:2 [
"number" => "1"
"description" => "The magic"
]
1 => array:2 [
"number" => "2"
"description" => "Forest in norway"
]
]
]
]
期望结果
array:9 [
"student_id" => "ST001"
"name" => "joe"
"books" => array:2 [
0 => array:2 [
"number" => "1"
"description" => "The magic"
]
1 => array:2 [
"number" => "2"
"description" => "Forest in norway"
]
]
]
我不知道如何删除St001
数组。我确实尝试过此$group_by[] = array(
,但books
数据将脱离数据结构。
答案 0 :(得分:1)
将内部数组分配给另一个数组。
$array = $array['ST001'];
答案 1 :(得分:0)
这将对您有帮助
foreach($book as $item)
{
$item['books'] = ['number' => $item['number'], 'description' => $item['description'], ];
if (!isset($group_by[$item['student_id']]))
{
$group_by[$item['student_id']] = array(
'student_id' => $item['student_id'],
'name' => $item['name'],
);
}
$group_by[$item['student_id']]['books'][] = $item['books'];
}
// remove key and get only value as you want
print_r(array_values($group_by));