Array search problem
$comedy = 'comedy, drama, thriller, action';
$array = array('action', 'fantas开发者_开发问答y', 'war', 'comedy', 'romance', 'drama', 'thriller');
I need to find the key words from each variable $comedy
.
I need:
3
5
6
0
Thank you!
What about the following portion of code :
$comedy = 'comedy, drama, thriller, action';
$array = array('action', 'fantasy', 'war', 'comedy', 'romance', 'drama', 'thriller');
foreach (explode(', ', $comedy) as $word) {
$index = array_search($word, $array);
var_dump($index);
}
Which gives me the following output :
int 3
int 5
int 6
int 0
Basically :
- As your words in the
$comedy
variables are always separated by the same pattern', '
, you can useexplode()
to get an array that contains those words. - Then, iterating over those words, you just have to call
array_search()
to get their position in your$array
array.
$comedy = 'comedy, drama, thriller, action';
$array = array('action', 'fantasy', 'war', 'comedy', 'romance', 'drama', 'thriller');
$tags = explode(', ', $comedy);
foreach ($tags as $tag)
{
echo array_search($tag, $array) . "\n";
}
This should do it.
You can find (and print) each of the indexes you want easily:
foreach (explode(', ', $comedy) as $keyword) {
echo array_find($keyword, $array);
}
If you want to associate each keyword with the index, you can do it this way:
$words = explode(', ', $comedy);
$indexes = array_map(
$words,
function($word) use ($array) { return array_find($keyword, $array); }
$assoc = array_combine($words, $indexes);
print_r($assoc);
The above requires PHP >= 5.3 for anonymous functions.
Why is comedy just a string?
I would just make comedy an array also and then make a loop that checks each value in the comedy against each value in the array.
精彩评论