如何搜索唯一数组键


How to search unique array key?

我正在尝试根据值获取数组的键。

$array1=array(
'0'=>'test1',
'1'=>'test2',
'2'=>'test3',
'3'=>'test1'
)
$array2=array(
'0'=>'11',
'1'=>'22',
'2'=>'33',
'3'=>'44'
)

我有

$source是针。它可以是"test1"、"test2"或"test3"

for loop to get different $source string
   if(in_array($source[$i], $array1)){
      $id=array_search($source[$i],$array1);
      //I want to output 11, 22 or 33 based on $source
      //However, my $array1 has duplicated value.
      //In my case, if $source is test1, the output will be 11,11 instead of 11 and 44
      echo $array2[$id]);
   }

我不知道如何解决这个问题。我的大脑被炸了。谢谢你的帮助!

PHP有一个函数:http://php.net/manual/en/function.array-keys.php

$keys = array_keys( $myArray, $theValue );,并且仅获得第一个:$keys[0];

这应该可以工作。

$array3 = array_flip(array_reverse($array1, true));
$needle = $source[$i];
$key = $array3[$needle];
echo $array2[$key];

array_flip所做的是交换密钥和值。如果值重复,则只交换最后一对。为了应对这种情况,我们使用array_reverse,但保留了密钥结构。

编辑:为了得到更多的澄清,这里有一个演习。

$array1=array(
'0'=>'test1',
'1'=>'test2',
'2'=>'test3',
'3'=>'test1'
)

array_reverse($array1, true)之后,输出将为

array(
'3' => 'test1',
'2' => 'test3',
'1' => 'test2',
'0' => 'test1'
)

现在,当我们翻转这个时,输出将是

array(
'test1' => '0', //would be 3 initially, then overwritten by 0
'test2' => '1',
'test3' => '2',
)