array_shift但保留密钥

2022-08-30 20:36:21

我的数组如下所示:

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

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

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

我怎样才能做到这一点?


答案 1
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
// 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);