首页 > 解决方案 > PHP - 当您使用 array_search 找到项目时如何获取数组值(如 [0]、[1]、[2])

问题描述

我试图尽可能具体,但我走了。

我有 2 个数组,fe:

$foo = array("a", "b", "c", "d", "e");
$fee = array("one", "two", "three", "four", "five");

'one' 匹配 'a','two' 匹配 'b','three' 匹配 'c' 等等。

假设我输入"abc"了文本输入。我如何获得"onetwothree"输出?
我刚在想。如果我可以得到输入文本的数组值,我可以用它来找到我想要的数组项。

如果这没有意义,我很抱歉,但对于那些理解的人,我感谢您的帮助。

更新(示例):

输入:'a'
输出:'one'

试图弄清楚:
在这种情况下,键值'a'为 [1]。
我想知道当我'a'使用array_search. 也许我正在使用更复杂的方式......欢迎任何建议更快地做到这一点!:)

标签: phparrayskey-value

解决方案


$foo = array('a', 'b', 'c', 'd', 'e');
$fee = array('one', 'two', 'three', 'four', 'five');

$output = '';
$text = 'abc';
  • 我们可以将文本拆分为一个数组,每个字符作为一个元素。
  • 搜索索引
  • 确保索引也存在于另一个数组中
  • 使用索引附加匹配的字符串。
foreach(str_split($text) as $char) {
    $index = array_search($char, $foo);
    if($index !== false && isset($fee[$index])) $output .= $fee[$index];
}

echo $output;

一二三


推荐阅读