2010-08-17 149 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