I have a small callback function which receives a comment in array like below:
$data[$count] = array(
'comment_id' => $comment['id'],
'comment_body' => $comment['message'],
'comment_author_id' => $comment['from']['id'],
'comment_author_name' => $comment['from']['name'],
'active' => 1,
'keyword_id' => null,
'live_video_id' => $liveVideo->live_vidoe_id
);
the I send this comment to a function AssignKeywords as below:
$data = array_map([$this , 'assignKeywords'], $data);
Below is the definition of AssignKeywords
public function assignKeywords($comment)
{
# code...
$keywords = Keyword::where('live_video_id' , $comment['live_video_id'])->get();
$commentBody = strtolower($comment['comment_body']);
preg_match_all('/(?<!\w)#\w+/',$commentBody,$matches); //it returns an associative array with just 0 index and array of matches on this 0 index
foreach($matches as $match) { //only 1
foreach ($match as $item) { //max 10 if a user is mad :\
foreach ($keywords as $keyword) { //Max 4
$keywordBody = strtolower($keyword['keyword_name']);
if ($item === $keywordBody) {
if ($comment['keyword_id'] == NULL) { //to check if it already contains a value, if it contains we don't want to assign again
$comment['keyword_id'] = $keyword['id'];
}
}
}
}
}
return $comment;
}<br>
I am looking for a better way to Assign Keywords and minimize foreach loops and maybe solve it by using functions? Any thoughts?