2010-06-16 45 views

回答

265

您可以使用unset

unset($array['key-here']); 

例子:

$array = array("key1" => "value1", "key2" => "value2"); 
print_r($array); 

unset($array['key1']); 
print_r($array); 

unset($array['key2']); 
print_r($array); 

輸出:

Array 
(
    [key1] => value1 
    [key2] => value2 
) 
Array 
(
    [key2] => value2 
) 
Array 
(
) 
+9

+1:感謝您的幫助。 PHP newb在這裏,但值得注意的是,如果你試圖在'foreach'循環中執行這些編輯,那麼你需要在enumeration變量前添加&符號以允許寫入權限。 – FreeAsInBeer 2012-07-30 21:20:46

+1

感謝FreeAsInBeer - 這爲我節省了30到60分鐘的搜索時間 – Igor 2012-11-11 22:36:01

4

使用unset

unset($array['key1']) 
1

您可能需要兩個或兩個以上的環根據您的陣列:

$arr[$key1][$key2][$key3]=$value1; // ....etc 

foreach ($arr as $key1 => $values) { 
    foreach ($key1 as $key2 => $value) { 
    unset($arr[$key1][$key2]); 
    } 
} 
+0

'foreach($ key1'似乎是錯誤的。是否意味着'foreach($ values')? – Pang 2016-05-06 06:52:05

12

使用此功能刪除鍵的特定陣列而不修改原始數組:

function array_except($array, $keys) { 
    return array_diff_key($array, array_flip((array) $keys)); 
} 

第一段m傳遞所有數組,第二個參數設置要移除的鍵數組。

例如:

$array = [ 
    'color' => 'red', 
    'age' => '130', 
    'fixed' => true 
]; 
$output = array_except($array, ['color', 'fixed']); 
// $output now contains ['age' => '130'] 
+1

您需要關閉'$ output = array_except($ array_1 ,['color','fixed']);' – 2016-07-27 07:05:50

+0

真高效的方法! – 2017-05-31 09:59:24

0

下面是消除了與偏移,長度和更換從關聯項目的方法 - 使用array_splice

function array_splice_assoc(&$input, $offset, $length = 1, $replacement = []) { 
 
     $replacement = (array) $replacement; 
 
     $key_indices = array_flip(array_keys($input)); 
 
     if (isset($input[$offset]) && is_string($offset)) { 
 
      $offset = $key_indices[$offset]; 
 
     } 
 
     if (isset($input[$length]) && is_string($length)) { 
 
      $length = $key_indices[$length] - $offset; 
 
     } 
 

 
     $input = array_slice($input, 0, $offset, TRUE) + $replacement + array_slice($input, $offset + $length, NULL, TRUE); 
 
      return $input; 
 
    } 
 

 
// Example 
 
$fruit = array(
 
     'orange' => 'orange', 
 
     'lemon' => 'yellow', 
 
     'lime' => 'green', 
 
     'grape' => 'purple', 
 
     'cherry' => 'red', 
 
); 
 

 
// Replace lemon and lime with apple 
 
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red')); 
 

 
// Replace cherry with strawberry 
 
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));

相關問題