2013-02-08 67 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