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

Vik*_*tor 6 php arrays associative-array function output

是否可以删除索引后的所有数组元素?

$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
Run Code Online (Sandbox Code Playgroud)

现在一些"神奇"

$myArray = delIndex(30, $myArrayInit);
Run Code Online (Sandbox Code Playgroud)

要得到

$myArray = array(1=>red, 30=>orange); 
Run Code Online (Sandbox Code Playgroud)

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

Please note:钥匙必须保留!+我只知道偏移钥匙!!

Sha*_*ran 22

不使用循环.

<?php
    $myArrayInit = [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);
Run Code Online (Sandbox Code Playgroud)

Output :

Array
(
    [1] => red
    [30] => orange
    [25] => velvet
)
Run Code Online (Sandbox Code Playgroud)

  • 我认为你的答案更好,因为它保留了关键的关联:) (4认同)

Nou*_*l.M 5

尝试

$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
Run Code Online (Sandbox Code Playgroud)

查看演示

  • **但是密钥不会被保留。** (2认同)
  • @viktor 更新了我的答案。但桑卡值得得到正确答案 (2认同)