2010-06-16 10 views

risposta

265

È possibile utilizzare unset:

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

Esempio:

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

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

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

uscita:

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

+1: Grazie per l'aiuto. PHP newb qui, ma vale la pena notare che se si sta tentando di eseguire queste modifiche all'interno di un ciclo 'foreach', è necessario anteporre una e commerciale alla variabile di enumerazione per consentire l'accesso in scrittura. – FreeAsInBeer

+1

Grazie a FreeAsInBeer - questo mi ha salvato da 30 a 60 minuti di ricerca – Igor

4

Utilizzando unset:

unset($array['key1']) 
1

Potrebbe essere necessario due o più cicli a seconda del vostro array:

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

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

'foreach ($ key1' sembra sbagliato. Intendevi' foreach ($ values'? – Pang

12

Usare questa funzione per rimuovere gli array specifici delle chiavi senza modificare l'array originale:

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

Primo para m passare tutti gli array, secondo set param array di tasti da rimuovere.

Ad esempio:

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

devi chiudere le virgolette su '$ output = array_except ($ array_1 , ['color', 'fixed']); ' –

+0

Modo davvero efficiente! –

0

Qui di seguito è un metodo che rimuove articoli di un associativa con offset, la lunghezza e la sostituzione - utilizzando 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'));

Problemi correlati