检查PHP多维数组中是否存在数组值

时间:2012-02-11 12:35:32

标签: php arrays multidimensional-array

我有以下多维数组:

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(因此该人是Jonah)并且他们的得分为5,我可以将5添加到已创建的数组值在id 0而不是创建新的数组值?

因此在循环完成后,数组将如下所示:

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

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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;
}

答案 2 :(得分: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);