我的数组看起来像这样:
$arValues = array( 345 => "jhdrfr", 534 => "jhdrffr", 673 => "jhrffr", 234 => "jfrhfr" );
Run Code Online (Sandbox Code Playgroud)
如何删除数组的第一个元素,但保留数字键?因为array_shift我的整数键值改为0, 1, 2, ....
我尝试unset( $arValues[ $first ] ); reset( $arValues );继续使用第二个元素(现在是第一个),但它返回false.
我怎样才能做到这一点?
biz*_*lop 17
reset( $a );
unset( $a[ key($a)]);
Run Code Online (Sandbox Code Playgroud)
更有用的版本:
// 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 ]);
Run Code Online (Sandbox Code Playgroud)
功能:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
小智 7
当我需要这样做时,我使用了:
unset($a[array_key_first($a)]);
Run Code Online (Sandbox Code Playgroud)
array_key_first()于 2018 年底在 PHP 7.3 中引入/可用。我不需要处理我的用例的指针,但是您仍然可以reset($a)在需要时运行。我没有看到任何最近的答案,所以我想添加这个。