2013-09-30 99 views
11

我的數組是這樣的:array_shift但保留鍵

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

如何刪除數組的第一個元素,但保留了數字鍵?由於array_shift將我的整數鍵值更改爲0, 1, 2, ...

我嘗試使用unset($arValues[ $first ]); reset($arValues);繼續使用第二個元素(現在第一個),但它返回false

我該如何做到這一點?

回答

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

多一點有用的版本:

// 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 ]); 

功能:

// 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

因爲我們特意要處理第一個元素。 'reset()'將數組ponter移動到第一個元素,'key()'返回該元素的索引。 – biziclop

+0

使用後,我調用'current($ a);'返回false。怎麼了? – Patrick

+0

我試着用google搜索,說明什麼是未設置後的當前元素,但什麼也沒找到。 「如果內部指針超出元素列表的末尾或數組爲空,則current()返回FALSE。」 – biziclop

0

這工作得很好,我...

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

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

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

輸出:

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

返回false也 – Patrick

+0

@Indianer你確定嗎?剛剛測試過,效果很好。 – pNre

+0

不,我的意思是在返回false之後調用current() – Patrick

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

這個函數使用biziclop的方法但返回鍵=>值對。