参见英文答案 >
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()的机会
请注意:钥匙必须保留!我只知道偏移钥匙!!
不使用循环.
原文链接:https://www.f2er.com/php/133293.html<?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 )