array_shift但保留键 [英] array_shift but preserve keys

查看:300
本文介绍了array_shift但保留键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组如下:

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

如何删除数组的第一个元素,但保留数字键?由于array_shift将我的整数键值更改为0, 1, 2, ....

How can I remove the first element of an array, but preserve the numeric keys? Since array_shift changes my integer key values to 0, 1, 2, ....

我尝试使用unset( $arValues[ $first ] ); reset( $arValues );继续使用第二个元素(现在是第一个),但是它返回false.

I tried using unset( $arValues[ $first ] ); reset( $arValues ); to continue using the second element (now first), but it returns false.

我该如何实现?

推荐答案

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; 
}

这篇关于array_shift但保留键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆