3 回答

TA貢獻1829條經驗 獲得超7個贊
讓我們用它來實現目標。array_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);
到目前為止,我們使用值來過濾數組。您也可以根據以下條件過濾數組。您需要對函數使用第三個參數。第 3 個參數有兩個選項 - 和 。您可以使用其中之一。讓我們使用 flag 來刪除基于 的項,例如:keyARRAY_FILTER_USE_KEYARRAY_FILTER_USE_BOTHARRAY_FILTER_USE_KEYkeytesting3
$filtered_array3 = array_filter($array, function($key) {
return 'testing3' != $key;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered_array3);
要了解有關功能的更多信息,請參閱此文檔array_filter()

TA貢獻1770條經驗 獲得超3個贊
您可以使用 (https://www.php.net/unsetunset)
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6');
unset($array['testing3']);
或者,如果您需要按可以使用的值找到它(https://www.php.net/array-searcharray_search)
// Remove the element if it exists
if($element = array_search("Template3",$array)){
unset($array[$element]);
}
要回答注釋中提出的有關僅保留您要查找的數組元素的問題:使用并覆蓋數組(或從中創建一個新數組)。array_search
$array = array_search('Template3', $array);
- 3 回答
- 0 關注
- 133 瀏覽
添加回答
舉報