2012-02-11 82 views
2

我有以下多維數組:檢查是否在一個PHP存在數組值多維數組

Array ([0] => Array 
     ([id] => 1 
      [name] => Jonah 
      [points] => 27) 
     [1] => Array 
     ([id] => 2 
      [name] => Mark 
      [points] => 34) 
    ) 

我目前使用一個foreach循環從數組提取值:

foreach ($result as $key => $sub) 
{ 
    ... 
} 

但我想知道如何查看數組中的值是否已經存在。

因此,舉例來說,如果我想另一組添加到數組,但ID爲1(這樣的人是喬納)和他們的得分是5,我可以在id 0加5到已經創建的數組值,而不是創建一個新的數組值?

於是經過循環完成數組將是這樣的:

Array ([0] => Array 
     ([id] => 1 
      [name] => Jonah 
      [points] => 32) 
     [1] => Array 
     ([id] => 2 
      [name] => Mark 
      [points] => 34) 
    ) 

回答

5

什麼循環您的陣列,檢查每個項目,如果它的id就是你要找的人?

$found = false; 
foreach ($your_array as $key => $data) { 
    if ($data['id'] == $the_id_youre_lloking_for) { 
     // The item has been found => add the new points to the existing ones 
     $data['points'] += $the_number_of_points; 
     $found = true; 
     break; // no need to loop anymore, as we have found the item => exit the loop 
    } 
} 

if ($found === false) { 
    // The id you were looking for has not been found, 
    // which means the corresponding item is not already present in your array 
    // => Add a new item to the array 
} 
+0

感謝您的建議帕斯卡,只有一個問題 - 如果我不知道數組的ID,有沒有辦法去通過所有的陣列,並檢查它匹配(例如'[ID] == 2'或'[name] == Mark')? – user1092780 2012-02-11 13:07:29

+1

你只需要改變條件,以反映你想要的;它會變成像'if($ data ['id'] == $ the_id_youre_lloking_for || $ data ['name'] == $ the_name_youre_looking_for)' – 2012-02-11 13:10:02

+0

非常棒,謝謝@Pascal的幫助! – user1092780 2012-02-11 13:14:21

1

您可以先存儲索引等於id的數組。 例如:

$arr =Array ([0] => Array 
    ([id] => 1 
     [name] => Jonah 
     [points] => 27) 
    [1] => Array 
    ([id] => 2 
     [name] => Mark 
     [points] => 34) 
); 
$new = array(); 
foreach($arr as $value){ 
    $new[$value['id']] = $value; 
} 

//So now you can check the array $new for if the key exists already 
if(array_key_exists(1, $new)){ 
    $new[1]['points'] = 32; 
} 
0

即使問題得到解答,我想發佈我的答案。未來的觀衆可能會很方便。您可以使用過濾器從該數組創建新數組,然後從那裏您可以檢查數組是否存在值。你可以按照下面的代碼。 Sample

$arr = array(
     0 =>array(
       "id"=> 1, 
       "name"=> "Bangladesh", 
       "action"=> "27" 
      ), 
     1 =>array(
       "id"=> 2, 
       "name"=> "Entertainment", 
       "action"=> "34" 
       ) 
     ); 

    $new = array(); 
    foreach($arr as $value){ 
     $new[$value['id']] = $value; 
    } 


    if(array_key_exists(1, $new)){ 
     echo $new[1]['id']; 
    } 
    else { 
     echo "aaa"; 
    } 
    //print_r($new);