php 如何删除数组的第一个元素而不更改其键值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18577087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:50:52  来源:igfitidea点击:

How to remove the first element of array without changing its key value?

phparrays

提问by Ganesh Babu

I have an array in php

我在 php 中有一个数组

<?php
$array=array("a"=>"123","b"=>"234","c"=>"345");
array_shift($array);
//array("0"=>"234","1"=>"345");
?>

If I use this function, then key value gets changed. I want my key value to remain the same. How can I remove first element without affecting array key values. My answer should be like

如果我使用这个函数,那么键值就会改变。我希望我的键值保持不变。如何在不影响数组键值的情况下删除第一个元素。我的答案应该是

array("b"=>"234","c"=>"345");

Note:Please do not use foreach(); I want to do this by existing array functions in php

注意:请不要使用 foreach(); 我想通过 php 中现有的数组函数来做到这一点

array_splice function is working for above array. But consider the below array

array_splice 函数适用于上述数组。但考虑下面的数组

<?php
$array = Array
(
    '39' => Array
        (
            'id' => '39',
            'field_id' => '620'

        ),

    '40' => Array
        (
            'id' => '40',
            'field_id' => '620',
            'default_value' => 'rrr',

));

array_splice($array, 0, 1);
print_r($array);
?>

It is showing answer as follows:

它显示的答案如下:

Array ( [0] => Array ( [id] => 40 [field_id] => 620 [default_value] => rrr ) )

May I know the reason?? Will array_splice() work only for single dimensional array?? Now key value is reset...

可以知道原因吗??array_splice() 是否仅适用于一维数组??现在键值被重置...

回答by aefxx

In case you do not know what the first item's keyis:

如果您不知道第一项key是什么:

// Make sure to reset the array's current index
reset($array);

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

回答by vikingmaster

$array=array("a"=>"123","b"=>"234","c"=>"345");
unset($array["a"]) ;
var_dump($array) ;

Also, what version of PHP do you use?

另外,您使用什么版本的PHP?

array_shiftworks fine for me with string-indexed arrays and I get the expected result.

array_shift使用字符串索引数组对我来说效果很好,我得到了预期的结果。

回答by Ganesh Babu

The solution for this question is as follows:

这个问题的解决方法如下:

<?php

unset($array[current(array_keys($array))]);

?>

It removes the first element without affecting the key values..

它删除第一个元素而不影响键值..

回答by Yatin Trivedi

<?php function array_kshift(&$array)
{
list($k) = array_keys($array);
$r  = array($k=>$array[$k]);
unset($array[$k]);
return $r;
}

// test it on a simple associative array
$array=array("a"=>"123","b"=>"234","c"=>"345");

array_kshift($array);
print_r($array);
?>