If I have an array $dictionary
and an array $words
how can I use an array ($words
) to index another array ($dictionary
)?
The easiest I can think is:
function dict_dispatch($word,$dictionary) {
return $dictionary[$word];
}
$translated = array_map('dict_dispatch', $words,
开发者_Python百科 array_fill(0, count($words), $dictionary));
e.g.
For example:
$dictionary = array("john_the_king"=>"John-The-King", "nick_great"=>"Nick-Great-2001");
$words=array("john_the_king","nick_great");
$translated = <??>
assert($translated==array("John-The-King","Nick-Great-2001"));
Notice that $dictionary might be quite large and it would be very nice if this operation is as fast as possible (that's why I don't use foreach in first place)
I don't know how efficient this is, but it works.
$translated = array_values(array_intersect_key($dictionary, array_flip($words)));
Are you talking about something like this where you use array of the keys and another for the values?
$translated = array_combine($words, $dictionary);
It looks like my original solution is more or less the most efficient.
精彩评论