2010-08-17 133 views
3

我試圖根據存儲在其中的值查找索引。根據值查找數組索引

這通常很容易,但我正在使用的數組是高度嵌套的。每個索引0,1,2都有字段f1,f2,f3。我試圖找到0,1,2在其f2字段中存儲的值this。在這種情況下,它是索引0。所以這是我正在尋找的輸出。在PHP中有這樣一個巧妙的技巧來有效地做到這一點嗎?

$somearray[0][f1] = "not this"; 
$somearray[0][f2] = "this"; 
$somearray[0][f3] = "not this"; 

$somearray[1][f1] = "not this"; 
$somearray[1][f2] = "not this"; 
$somearray[1][f3] = "not this"; 

$somearray[2][f1] = "not this"; 
$somearray[2][f2] = "not this"; 
$somearray[2][f3] = "not this"; 

回答

3

在這種情況下,它的指數爲0。所以這就是 我要找的輸出。

$somearray[0]['f1'] = "not this"; 
$somearray[0]['f2'] = "this"; 
$somearray[0]['f3'] = "not this"; 

$somearray[1]['f1'] = "not this"; 
$somearray[1]['f2'] = "not this"; 
$somearray[1]['f3'] = "not this"; 

$somearray[2]['f1'] = "not this"; 
$somearray[2]['f2'] = "not this"; 
$somearray[2]['f3'] = "not this"; 

foreach($somearray as $key => $value) 
{ 
    if($value['f2'] === 'this') 
    { 
    echo $key; // find out the key 
    } 
} 

輸出:

0 
+0

謝謝。做我想做的事情。 – lok 2010-08-18 01:19:47

+0

@lok:不客氣:) – Sarfraz 2010-08-18 04:37:27