PHP:如何删除索引后的所有数组元素 [英] PHP: How to delete all array elements after an index
本文介绍了PHP:如何删除索引后的所有数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ myArrayInit = array(1 => red, 30 =>橙,25 =>天鹅绒,45 =>粉红色);
现在有些神奇
$ myArray = delIndex(30,$ myArrayInit);
得到
$ myArray = array(1 => red,30 => orange);
由于 $ myArray
中的键是不是连续的,我没有看到 array_slice()
请注意
:键必须保留! +我只知道Offset Key!
解决方案
不使用循环。
<?php
$ myArrayInit = array(1 =>'red',30 =>'orange',25 = '天鹅绒',45 =>'粉红色'); //< - 您的实际数组
$ offsetKey = 25; //< ---你需要获取的偏移量
//允许执行代码....
$ n = array_keys($ myArrayInit); //< ----获取实际数组的所有键并放入另一个数组
$ count = array_search($ offsetKey,$ n); //< ---使用搜索返回数组中偏移量的位置
$ new_arr = array_slice($ myArrayInit,0,$ count + 1,true); //< 0索引作为起始位置,位置+1作为长度参数。
print_r($ new_arr);
OUTPUT:
数组
(
[1] =>红色
[30] = > orange
[25] =>天鹅绒
)
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray
are not successive, I don't see a chance for array_slice()
Please note
: Keys have to be preserved! + I do only know the Offset Key!!
解决方案
Without making use of loops.
<?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,0,$count+1,true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
OUTPUT :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
这篇关于PHP:如何删除索引后的所有数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文