2013-02-22 21 views
0

假設我有一個數組類似下面:訪問對應值給出某個已知值

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [title] => Group1 
      [description] => This is the group1. 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [title] => Group2 
      [description] => This is group2. 
     ) 

) 

假設標題被稱爲「組2」。如果我不能確定它的等效描述(即「這是group2」),如果它不知道其關鍵字,標識等僅有標題,我該如何確定?

感謝您的任何幫助。

+2

遍歷數組,並檢查*標題*鍵是**組2 **,如果是簡單地得到說明 – kjetilh 2013-02-22 08:53:08

回答

3

試試這個:

$title = "Group2"; 

foreach($your_array as $val){ 
    if($val['title'] == $title){ 
     echo $val['description']; 
     break; //cut back on unnecessary looping 
    } 
} 
0

你必須遍歷主陣列上,然後掃描該稱號。

假設你的主數組被稱爲$groups

$title = 'Group2'; 
foreach($groups as $key => $group){ 
    if ($group['title'] == $title){ 
    $groupDescription = $group['description']; 
    // if you need to reference this group again, save it's key. 
    $groupKey = $key; 
    } 
} 

您可以將break命令你找到你正在尋找終止循環,這樣就不會繼續掃描陣列組後後你找到了你正在尋找的那個。

+1

我需要休息添加到您的嗎? :] – 2013-02-22 08:56:28

+1

@nic - 這一切都取決於OP想要對羣體做什麼。我已經添加了關於break命令的註釋...但是請不要編輯其他用戶代碼塊 - 而是留下評論(就像您在我的那樣),並讓用戶決定是否要將其添加到他們的回答。 – Lix 2013-02-22 08:58:00

0

嘗試這樣

foreach($myarray as $val){ 
    if($val['title'] == "Group2"){ 
    echo 'This is description '.$val['description']; 
    } 
} 
+0

在這裏,你不需要像key和vlaue那樣分離它們,但是甚至可以作爲搜索的值 – Gautam3164 2013-02-22 08:56:22