检查PHP多维数组中是否存在数组值
我有以下多维数组:检查PHP多维数组中是否存在数组值,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有以下多维数组: Array ( [0] => Array ( [id] => 1 [name] => Jonah [points] => 27 ) [1] => Array ( [id] => 2 [name] => Mark [points] => 34 ) ) 我目前正在使用f
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添加到ID0
中已经创建的数组值中,而不是创建新的数组值吗
因此,循环完成后,数组将如下所示:
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
}
您可以首先存储索引等于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;
}
即使问题已经回答了,我还是想把我的答案贴出来。可能对未来的观众有用。您可以使用过滤器从此数组创建新数组,然后从中检查该数组上是否存在值。您可以遵循以下代码
谢谢你的建议,Pascal,只有一个问题-如果我不知道数组的id,有没有办法检查所有数组并检查它是否匹配(例如
[id]==2
或[name]==Mark
)?你只需更改条件,以反映你想要的;如果($data['id']=$你要找的id$data['name']=$你要找的名字)
$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);