2014-11-03 118 views
1

美好的一天。我有一個多維數組PHP:按值輸入獲取數組鍵。

Array ([0] => stdClass Object ([id] => 1 [title] => "Title1") 
     [1] => stdClass Object ([id] => 3 [title] => "Title2") 
     [2] => stdClass Object ([id] => 4 [title] => "Title3") 
    ) 

我怎樣才能從數組中獲取數組的數量。

例如:如何讓[2]在[id] => 1上有[id] => 4或0?

回答

1

天真搜索:

$id = 4; 
foreach($array as $k=>$i) { 
    if ($i->id == $id) 
    break; 
} 

echo "Key: {$k}"; 

請注意,此解決方案可能會比其他的答案快,因爲它只要它發現它打破。

+0

謝謝,已經在行動中測試過,這就是我所需要的。 – RQEST 2014-11-03 13:16:51

+0

「投票需要15點聲望」。我只有3個。 – RQEST 2014-11-03 13:51:59

0

您可以通過重複原始數組創建一個新的陣列來映射ID,以指標:

$map = []; 
foreach($array as $key=>$value) 
    $map[$value->id]=$key; 

echo 'object with id 4 is at index ' . $map[4]; 
echo 'object with id 1 is at index ' . $map[1]; 

如果你想查找一個以上的ID,這是比迭代原數組更有效每一次。

如果你想從ojects訪問其他數據,你可以將它們存儲新的數組中,INSEAD存儲索引:

$objects = []; 
foreach($array as $obj) 
    $objects[$obj->id]=$obj; 

echo 'object with id 4 has the following title: ' . $obj[4]->title; 
echo 'object with id 1 has the following title: ' . $obj[1]->title; 
1
function GetKey($array, $value) { 
    foreach($array as $key => $object) { 
     if($object->id == $value) return $key; 
    } 
} 

$key = GetKey($array, 4); 

此功能運行遍佈對象,如果ID匹配你提供的那個,然後它返回密鑰。