2013-09-30 8 views
11

La mia matrice aspetto:array_shift ma preservare chiavi

$arValues = array(345 => "jhdrfr", 534 => "jhdrffr", 673 => "jhrffr", 234 => "jfrhfr"); 

Come posso rimuovere il primo elemento di un array, ma conservare i tasti numerici? Poiché array_shift modifica i valori della mia chiave intera su 0, 1, 2, ....

Ho provato a utilizzare unset($arValues[ $first ]); reset($arValues); per continuare a utilizzare il secondo elemento (ora per primo), ma restituisce false.

Come posso ottenere questo risultato?

risposta

13
reset($a); 
unset($a[ key($a)]); 

versione Un po 'più utile:

// rewinds array's internal pointer to the first element 
// and returns the value of the first array element. 
$value = reset($a); 

// returns the index element of the current array position 
$key = key($a); 

unset($a[ $key ]); 

Funzioni:

// returns value 
function array_shift_assoc(&$arr){ 
    $val = reset($arr); 
    unset($arr[ key($arr) ]); 
    return $val; 
} 

// returns [ key, value ] 
function array_shift_assoc_kv(&$arr){ 
    $val = reset($arr); 
    $key = key($arr); 
    $ret = array($key => $val); 
    unset($arr[ $key ]); 
    return $ret; 
} 
+2

Perché in particolare vogliamo gestire il primo elemento. 'reset()' sposta il ponter di array sul primo elemento, 'key()' restituisce l'indice di quell'elemento. – biziclop

+0

Dopo averlo usato, chiamo 'current ($ a);' che restituisce false. Cosa c'è che non va? – Patrick

+0

Ho provato rapidamente su google che quello che sarà l'elemento corrente dopo lo spegnimento, ma non ha trovato nulla. "Se il puntatore interno punta oltre la fine dell'elenco degli elementi o l'array è vuoto, current() restituisce FALSE." – biziclop

0

Questo funziona bene per me ...

$array = array('1','2','3','4'); 

reset($array); 
$key = key($array); 
$value = $array[$key]; 
unset($array[$key]); 

var_dump($key, $value, $array, current($array)); 

uscita:

int(0) 
string(1) "1" 
array(3) { [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" } 
string(1) "2" 
6
// 1 is the index of the first object to get 
// NULL to get everything until the end 
// true to preserve keys 
$arValues = array_slice($arValues, 1, NULL, true); 
+0

restituisce false anche ... – Patrick

+0

@Indianer sei sicuro? Appena testato e funziona bene. – pNre

+0

no intendo chiamare current() dopo che restituisce false – Patrick

0
function array_shift_associative(&$arr){ 
reset($arr); 
$return = array(key($arr)=>current($arr)); 
unset($arr[key($arr)]); 
return $return; 
} 

Questa funzione utilizza il metodo di biziclop ma restituisce una coppia di valori chiave =>.

Problemi correlati