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?
-
\$\begingroup\$ It might be useful for you to add more context (for example the entire class that is involved here) in order to get more meaningful review. \$\endgroup\$Mike Brant– Mike Brant2017年03月23日 23:15:44 +00:00Commented Mar 23, 2017 at 23:15
1 Answer 1
From performance point of view, 40 iterations is nothing.
However, given such a condition that your keywords are like the Highlanders, as there could be only one, the number of repetitions could be reduced as we won't need anymore after we get one.
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) {
$comment['keyword_id'] = $keyword['id'];
break 3; // stop all loops
}
}
}
}
}
Explore related questions
See similar questions with these tags.