I wanted to insert the id
values of $courseCat
if that id is not present in $m
.In the below code, i feel the $m
array is getting emptied every time and so, all id's are getting inserted to the $m
,as the result of dump($m)
indicates.How can i fix this?
$m=[];
$courseCat = MyCourse::where('course_id', $key['courseId'])->get()->toArray();
foreach($courseCat as $k=>$c){
// dump($courseCat);
if(!in_array($c['id'],$m)){
array_push($m,$c['id']);
}
}
//dump($m);
dump($courseCat);
shows the following result
array:2 [
0 => array:19 [
"id" => 2
"course_id" => 18
]
1 => array:19 [
"id" => 3
"course_id" => 18
]
]
array:2 [
0 => array:19 [
"id" => 2
"course_id" => 18
]
1 => array:19 [
"id" => 3
"course_id" => 18
]
]
array:2 [
0 => array:19 [
"id" => 5
"course_id" => 1
]
1 => array:19 [
"id" => 6
"course_id" => 1
]
]
array:2 [
0 => array:19 [
"id" => 5
"course_id" => 1
]
1 => array:19 [
"id" => 6
"course_id" => 1
]
]
dump($m)
shows the below result:
array:2 [
0 => 2
1 => 3
]
array:2 [
0 => 2
1 => 3
]
array:2 [
0 => 6
1 => 5
]
array:2 [
0 => 6
1 => 5
]
Below attached images are the result of the query MyCourse::where('course_id', $key['courseId'])->get()
.
[enter image description here]1
[enter image description here]2
[enter image description here]3
Expected result :
dump($m)
should show the below result
[0=>2,
1=>3,
2=>5,
3=>6]
CodePudding user response:
I think it's because you have an outer loop not shown in the question. You need to declare $m
before the outer loop:
$m=[];
foreach($keys as $key){
$courseCat = MyCourse::where('course_id', $key['courseId'])->get()->toArray();
foreach($courseCat as $k=>$c){
if(!in_array($c['id'],$m)){
array_push($m,$c['id']);
}
}
}
dump($m);
CodePudding user response:
If you want all the values of a column from your query you can use pluck
:
MyCourse::where('course_id', $key['courseId'])->pluck('id')
Now you have a list of all the 'id's.
Laravel 8.x Docs - Database - Running Database Queries - Retrieving a List of Column Values pluck