2012-02-11 87 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);