加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:41:01 所属栏目: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); 要得到 $my
参见英文答案 > 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
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读