检查是否在一个PHP多维数组存在数组值 [英] Checking if array value exists in a PHP multidimensional array

查看:176
本文介绍了检查是否在一个PHP多维数组存在数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下多维数组:

 阵列([0] =>数组
         ([ID] => 1
           [名] =>约拿
           [要点] => 27)
        [1] =>排列
         ([ID] => 2
           [名] =>标记
           [要点] => 34)
      )

我目前使用的是的foreach 循环来提取数组中的值:

 的foreach($结果为$关键=> $分)
{
    ...
}

但我不知道我怎么看阵列内的值是否已经存在。

因此​​,举例来说,如果我想另一组添加到数组,但id为 1 (这样的人是约拿)和他们的成绩是5,可我添加5已创建数组值 ID 0 而不是创建一个新的数组值?

所以循环完成后,阵列将是这样的:

 阵列([0] =>数组
         ([ID] => 1
           [名] =>约拿
           [要点] => 32)
        [1] =>排列
         ([ID] => 2
           [名] =>标记
           [要点] => 34)
      )


解决方案

什么循环您的数组,检查每一个项目,如果它是 ID 是你是我的唯一找谁?

  $发现= FALSE;
的foreach($ your_array为$关键=> $数据){
    如果($数据['身份证'] == $ the_id_youre_lloking_for){
        //该项目已发现= GT;添加新的指向现有
        $数据['点'] + = $ the_number_of_points;
        $找到= TRUE;
        打破; //无需环路了,因为我们已经找到了项目=>退出循环
    }
}如果($找到=== FALSE){
    //你要找的人的ID没有被发现,
    //这意味着相应的项目是不是已经present阵列中
    // =>添加一个新的项目到数组
}

I have the following multidimensional array:

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

I'm currently using a foreach loop to extract the values from the array:

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

But I was wondering how do I see whether a value within the array already exists.

So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?

So after the loop has finished the array will look like this:

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

解决方案

What about looping over your array, checking for each item if it's id is the one you're looking for ?

$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
}

这篇关于检查是否在一个PHP多维数组存在数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆