use*_*780 2 php arrays multidimensional-array
我有以下多维数组:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
Run Code Online (Sandbox Code Playgroud)
我正在使用foreach循环从数组中提取值:
foreach ($result as $key => $sub)
{
...
}
Run Code Online (Sandbox Code Playgroud)
但我想知道如何查看数组中的值是否已存在.
所以例如,如果我想向数组中添加另一个集合,但是id是1(所以这个人是Jonah)并且他们的分数是5,我可以将5添加到已创建的数组值id 0而不是创建新的数组值?
所以在循环完成后,数组将如下所示:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
Run Code Online (Sandbox Code Playgroud)
怎么样循环你的数组,检查每个项目是否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
}
Run Code Online (Sandbox Code Playgroud)