2013-02-08 71 views
0

我想获得基于值的数组的关键。如何搜索唯一的数组键?

$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]); 
    } 

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

回答

1

这应该工作。

$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', 
) 
+0

感谢您的提示!但在阅读array_flip()的手册后,我会说array_flip对于大多数应用程序来说不是一个好主意,因为只有字符串或数字被允许作为值。然而,在**这个**的情况下,它会工作 – hek2mgl 2013-02-08 20:59:59

+0

是的,但在这种情况下,这些值本身,是“字符串”。对于这个问题,它不适用于'Object'或'Arrays'数组。 – Achrome 2013-02-08 21:01:55