2013-09-30 97 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的方法但返回键=>值对。