我有以下多维数组:
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 )
)
循环遍历数组,检查每个项目(如果是)怎么样?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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)