PHP:如何删除索引后的所有数组元素

参见英文答案 > php – how to remove all elements of an array after one specified3个
是否可以删除索引后的所有数组元素?
$myArrayInit = array(1=>red,30=>orange,25=>velvet,45=>pink);

现在一些“神奇”

$myArray = delIndex(30,$myArrayInit);

要得到

$myArray = array(1=>red,30=>orange);

由于$myArray中的键不是连续的,我没有看到array_slice()的机会

请注意:钥匙必须保留!我只知道偏移钥匙!!

不使用循环.
<?PHP
$myArrayInit = array(1=>'red',30=>'orange',25=>'velvet',45=>'pink'); //<-- Your actual array
$offsetKey=25; //<--- The offset you need to grab
//Lets do the code....
$n=array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count=array_search($offsetKey,$n); //<--- Returns the position of the offset from this array using search
$new_arr=array_slice($myArrayInit,$count+1,true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);

输出

Array
(
    [1] => red
    [30] => orange
    [25] => velvet
)

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...