我正在制作电影WebApp。用户选择电影并将其添加到数据库中。列movie_list
是JSON,因为
我希望每次用户添加电影时,它都会被添加到数组中,如果已经存在,我希望它不会被添加到数组中。
问题在于,不是将其添加到现有数组中,而是有时会覆盖该数组,仅添加嵌套的数组或仅创建自定义键(0,1,2,3)
。
我试图发挥作用
array_merge and array_add
// It does overwrite it
array['checkedMovie'] = 3
每个人都在考虑,但可悲的是不知道如何实现。
我的大脑被挤压了。
public function update(Request $request, TrackMovie $trackMovie)
{
$currentCheckedMoviesArray = DB::table('track_movies')->where('user_id', $trackMovie->user_id)->get('checkedMovie');
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
$newarraychecked=array_add($currentCheckedMoviesArray,$currentCheckedMoviesArray['checkedMovie'], $trackMovie->checkedMovie);
return dd($newarraychecked);
$current_length = DB::table('track_movies')->where('user_id', $trackMovie>user_id)->value('lengthOfMovie');
DB::table('track_movies')->where('user_id', $trackMovie->user_id)->update([
'lengthOfMovie' => $current_length + $trackMovie->lengthOfMovie,
'checkedMovie' => $newarraychecked;
]);
return dd(TrackMovie::all());
}
为了使它清晰一点,我对其进行了编辑,因为我认为是因为我的格式。
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
// DD Result
array:1 [▼
"checkedMovie" => "["1", "2"]"
]
$trackMovie->checkedMovie
//DD Result
array:2 [▼
0 => "2"
1 => "4"
]
$newarraychecked=Arr::collapse($currentCheckedMoviesArray, $trackMovie->checkedMovie);
//DD Result
[]
实际结果:
This is the result what I get on the above code
array:1 [▼
"checkedMovie" => "["1", "2"]"
]
There some more because I tested many things
array:1 [▼
"checkedMovie" => "["1", "2"]"
1 => "2"
2 => "4"
]
预期结果:
The User is checking some movies.
// He already has some movies
checkedMovie = ["1","2","3"]
Now the Application Checks if it already existed the movie in the Database.
If it does not contain in the database I want to add it. User selects Movie ID (5,6)
checkedMovie = ["1","2","3","5","6"]
After that, it will overwrite the Database column value
如果我忘记了要添加到问题中的内容,请对其进行评论,以便我可以编辑问题!
答案 0 :(得分:0)
您可以将新值推送到数组,然后使用array_unique过滤出重复项
示例:
public function update(Request $request, TrackMovie $trackMovie)
{
//Get Current Array from DB
$currentCheckedMoviesArray = DB::table('track_movies')->where('user_id', $trackMovie->user_id)->get('checkedMovie');
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
//Decode JSON array
$currentCheckedMoviesArray['checkedMovie'] = json_decode($currentCheckedMoviesArray['checkedMovie'])
//Push the new Movie to the array
$currentCheckedMoviesArray['checkedMovie'][] = $trackMovie->checkedMovie;
//Remove duplicates from the array
$newarraychecked = array_unique($currentCheckedMoviesArray['checkedMovie']);
....
}
答案 1 :(得分:0)
尝试以下操作:
$checkedMovie=array(1,2,3);
$selectedMovie=array(3,4,5,6);
$checkedMovie=array_unique(array_merge($checkedMovie,$selectedMovie));