Temor wrote:but every way I turn this it requires me to run a loop inside a loop, which as far as I know is not possible.
It's very possible !
for ($x = 1; $x < 10; ++$y){
echo '<div>';
for ($y = 0; $y < $x; ++$y){
echo '* ';
}
echo '</div>';
}
Try that out
You can use substr_count too, example
$search = array('This', 'is', 'a', 'search', 'term');
$results = array(
array(
'title' => 'This is a video title.',
'description' => 'This is a video description. It contains words and stuff.',
),
array(
'title' => 'Words. Wooo!',
'description' => 'This is also a video description.',
),
);
foreach ($results as &$result){
$matches = 0;
foreach ($result as $string){
foreach ($search as $term){
$matches += substr_count($string, $term);
}
}
$result['matches'] = $matches;
}
print_r($results);
problem is this does not count words, it counts occurrences of a string so not that useful but for the fun of it lets simplify using array_map
$search = array('This', 'is', 'a', 'search', 'term');
$results = array(
array(
'title' => 'This is a video title.',
'description' => 'This is a video description. It contains words and stuff.',
),
array(
'title' => 'Words. Wooo!',
'description' => 'This is also a video description.',
),
);
foreach ($results as &$result){
$result['matches'] = array_sum(array_map('substr_count', array_fill(0, count($search), $result['title']), $search));
$result['matches'] += array_sum(array_map('substr_count', array_fill(0, count($search), $result['description']), $search));
}
print_r($results);
Okay I lied that's not simpler.
The most working way to do it is probably to split each string up into words and compare each one.
$search = array('This', 'is', 'a', 'search', 'term');
$results = array(
array(
'title' => 'This is a video title.',
'description' => 'This is a video description. It contains words and stuff.',
),
array(
'title' => 'Words. Wooo!',
'description' => 'This is also a video description.',
),
);
foreach ($results as &$result){
$string = implode(' ', $result);
$result['matches'] = 0;
preg_match_all('#[a-z]+#i', $string, $matches);
foreach ($matches[0] as $word){
if (in_array($word, $search)){
++$result['matches'];
}
}
}
print_r($results);
But this is case sensitive so you would need to make sure your search term was strtolower()ed as were all the results when comparing...
Good luck