php中fitler数组的数组过滤器
如何从php中的以下数组中删除基于键(例如,php中fitler数组的数组过滤器,php,Php,如何从php中的以下数组中删除基于键(例如,$array[testing3])或基于值(例如,Template3)的项 $array = array( 'mentor' => 'Template', 'mentor1' => 'Template1', 'testing' => 'Template2', 'testing3' => 'Template3', 'testing4' => 'Template4', 'test
$array[testing3]
)或基于值(例如,Template3
)的项
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6'
);
您可以使用unset()来实现这一点:
unset(myArray['testing3']);
您可以使用
unset
()
或者,如果需要通过值查找,可以使用数组搜索()
要回答评论中提出的仅保留要查找的数组元素的问题,请执行以下操作:
使用array\u search
覆盖您的数组(或从中创建新数组)
让我们使用array\u filter()
来实现这个目标
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6'
);
删除数组中的项目,例如,Template3
$filtered_array1 = array_filter($array, function($val) {
return 'Template3' != $val;
});
print_r($filtered_array1);
从数组中删除除Template3
之外的数组中的所有元素
$filtered_array2 = array_filter($array, function($val) {
return 'Template3' == $val;
});
print_r($filtered_array2);
到目前为止,我们使用value来过滤数组。您也可以基于键
筛选数组。您需要对函数使用第三个参数。第三个参数有两个选项-ARRAY\u FILTER\u USE\u KEY
和ARRAY\u FILTER\u USE\u两者都
。你可以用其中一个。让我们使用ARRAY\u FILTER\u use\u KEY
标志根据KEY
删除项目,例如,testing3
:
$filtered_array3 = array_filter($array, function($key) {
return 'testing3' != $key;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered_array3);
要了解有关array\u filter()
函数的更多信息,请参阅此如果您不知道密钥名称并希望按值删除,请使用Jeff的其他答案如果在数组中未找到“Template3”,则将取消设置$array[0]
(如果存在)。您应该检查array\u search
的结果是否为false。如何从数组中删除数组中除Template3以外的所有元素?@James使用array\u filter()
您可以这样做。@unclexo为什么不将数组重置为testing3?e、 g.$array=array('testing3'=>'Template3')
或array\u search(例如,$array=array\u search('Template3',$array);
当您同时知道键和值时,可以这样做。但有时您不知道其中一个。因此,键或值可以是动态的。否则,您可以使用array\u filter()更好地操作数组项
。您应该将您满意的答案标记为正确。我很惊讶没有一个答案提到或更正了重复的密钥。
$filtered_array1 = array_filter($array, function($val) {
return 'Template3' != $val;
});
print_r($filtered_array1);
$filtered_array2 = array_filter($array, function($val) {
return 'Template3' == $val;
});
print_r($filtered_array2);
$filtered_array3 = array_filter($array, function($key) {
return 'testing3' != $key;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered_array3);