[英]How to delete previous all elements from a specified index in PHP?
I have an array and I want to delete previous all elements from the current specified index 我有一个数组,我想从当前指定的索引中删除以前的所有元素
For example: 例如:
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
I have an index like 3
, so I want to delete previous all like 我有一个像
3
的索引,所以我想删除以前的所有类似
0 => "a", 1 => "b", 2 => "c"
and only have 并且只有
3=>"d", 4=>"e"
in my new array. 在我的新阵列中。 Can anyone help me?
谁能帮我?
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3);
output: 输出:
array(2) {
[0]=> string(1) "d"
[1]=> string(1) "e"
}
Another solution with saving index 保存索引的另一种解决方案
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3, null, true);
output: 输出:
array(2) {
[3]=> string(1) "d"
[4]=> string(1) "e"
}
https://www.php.net/manual/en/function.array-slice.php https://www.php.net/manual/en/function.array-slice.php
You may to use array_slice() 你可以使用array_slice()
In example : 例如:
<?php
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$startingPosition = 3;
// Preserve keys
// |
// Your array Delete from Delete to |
// | | (if null, |
// | | to the end) |
// | | | |
// v v v v
$array = array_slice($array, $startingPosition , null, true);
var_dump($array);
Output : 输出:
array(2) {
[3]=>
string(1) "d"
[4]=>
string(1) "e"
}
You can use veriation of array-slice and so on (as array_slice($array, 3)
) but also simple for loop: 您可以使用数组切片等的验证(如
array_slice($array, 3)
),但也可以使用简单的循环:
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$copy = false;
foreach($array as $k => $v) {
$copy |= ($k == 3);
if ($copy)
$res[$k] = $v;
}
You can also use unset() to remove the elements. 您还可以使用unset()删除元素。 As shown below.
如下所示。
<?php
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$index = 3;
for($i = 0; $i<$index; $i++)
{ unset($array[$i]); }
echo "<pre>";print_r($array);
?>
You can use array_slice : 你可以使用array_slice :
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$newArray = array_slice($array, 3, NULL, TRUE);
echo '<pre>';
print_r($newArray);
echo '</pre>';
Output: 输出:
Array
(
[3] => d
[4] => e
)
Note that 4 th parameter: TRUE -> preserve_keys is very important.
注意第4个参数:TRUE - > preserve_keys非常重要。
If it is set to true, preserves the keys in the output array. 如果设置为true,则保留输出数组中的键。
Your new array will now have all elements only after index 3
现在,您的新数组将仅在索引
3
之后包含所有元素
All elements before 3
are not returned here. 此处不返回
3
之前的所有元素。
Try this 试试这个
<?php
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$new_array = array_slice($array, 3); // 3 is your key to slice
print_r($new_array);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.