php使用数组作为数组的索引
如果我有一个数组php使用数组作为数组的索引,php,arrays,Php,Arrays,如果我有一个数组$dictionary和一个数组$words,我如何使用一个数组($words)来索引另一个数组($dictionary) 我能想到的最简单的方法是: function dict_dispatch($word,$dictionary) { return $dictionary[$word]; } $translated = array_map('dict_dispatch', $words, array_fill(0
$dictionary
和一个数组$words
,我如何使用一个数组($words
)来索引另一个数组($dictionary
)
我能想到的最简单的方法是:
function dict_dispatch($word,$dictionary) {
return $dictionary[$word];
}
$translated = array_map('dict_dispatch', $words,
array_fill(0, count($words), $dictionary));
e、 g
例如:
$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"));
$dictionary=array(“约翰·王”=>“约翰·王”、“尼克·伟大”=>“尼克·伟大-2001”);
$words=array(“约翰·王”、“尼克·伟大”);
$translated=
assert($translated==array(“约翰·金”,“尼克·格瑞特-2001”);
请注意,$dictionary可能非常大,如果这个操作尽可能快的话(这就是为什么我不首先使用foreach)您是说在哪里使用键数组和另一个值数组
$translated = array_combine($words, $dictionary);
我不知道这有多有效,但它确实有效
$translated = array_values(array_intersect_key($dictionary, array_flip($words)));
看起来我的原始解决方案或多或少是最有效的。你是说你想从另一个数组中构造一个数组,使用一个索引数组吗?你能举个小例子说明你会得到什么数据以及你希望得到什么吗?非常感谢,我刚刚添加了一个示例,您的代码有什么问题吗?它是正确的-但我想知道是否有比Ruby/Python更原生/更快的东西…非常感谢!不完全是。为了清晰起见,我添加了一个例子。这很好,但有点棘手,因为数组翻转很顽皮,如果我们使用例如$words=array(“john_the_king”、“nick_great”、“john_the_king”);据我所知,它似乎相当有效。事实上,使用
microtime()
进行的快速测试表明,它比OP的代码慢了一点。@neverlastn:我没有想到,是的,那会是个问题。