我几天来一直试图解决这个问题。我无处可去。我的网站可以选择在学校选择哪些科目:前端部分很有效,我可以将结果保存在subjects
列中的表格中。
添加多个主题时会出现问题:它会为我添加的每个主题创建一个子项。这个,当添加一些主题时会产生如下结果:
[
{
"subject": {
"level": "hl",
"subject": "mathematics"
}
},
[
{
"subject": {
"level": "hl",
"subject": "french"
}
},
[
{
"subject": {
"level": "hl",
"subject": "history"
}
}
]
]
]
正如您所看到的,每次用户添加主题时,都会创建一个子项以保留之前添加的任何主题。我想要实现的是这样的:
[
{
"subject": {
"level": "hl",
"subject": "mathematics"
}
},
{
"subject": {
"level": "hl",
"subject": "french"
}
},
{
"subject": {
"level": "hl",
"subject": "history"
}
}
]
我用于将两个数组合并在一起的PHP代码如下:
//The user selected subject
$input = $request->only(['subject', 'level']);
//Make a user model
$user = Auth::user();
//Format for array
$add_subject['subject'] = [
'subject' => $input['subject'],
'level' => $input['level'],
];
//Get the subjects the user already has from the user model
$user_subjects = $user->subjects;
//Make the two arrays
$array1 = array($add_subject);
$array2 = array($user_subjects);
//Merge the two arrays
$merge = array_merge($array1, $array2);
//Save the array in database
$user->subjects = $merge;
$user->save();
基本上我的代码目前正在为每个主题创建一个数组。有没有办法防止它发生?
答案 0 :(得分:3)
您的代码存在问题:
$array2 = array($user_subjects);
正如我猜测$ user_subjects已经是一个数组,所以你要把它变成一个里面有数组的数组。
此外,您实际上不需要使用array_merge
。这也应该有效:
$user_subjects[] = $add_subject;
答案 1 :(得分:0)
只需这样做:
//The user selected subject
$input = $request->only(['subject', 'level']);
//Make a user model
$user = Auth::user();
// add item to user's subjects
$user->subjects[] = [
'subject' => $input['subject'],
'level' => $input['level'],
];
//Save the array in database
$user->save();