php - 如何在指定之后删除数组的所有元素

Lee*_*Tee 3 php associative-array

我有一个像这样的数组:

数组([740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 [730106] => subsubcat [740107] =>和另一个[730109] =>测试猫)

我想删除元素之后的所有元素元素,键是'720102'.所以阵列将成为:

数组([740073] => Leetee Cat 1 [720102] => cat 1 subcat 1)

我怎么做到这一点?到目前为止我只有这个...

foreach ($category as  $cat_id => $cat){
    if ($cat_id == $cat_parent_id){
    //remove this element in array and all elements that come after it 
    }
}
Run Code Online (Sandbox Code Playgroud)

[编辑]第一个答案似乎适用于大多数情况,但不是全部.如果原始数组中只有两个项,则只删除第一个元素,但不删除后面的元素.如果只有两个元素

数组([740073] => Leetee Cat 1 [740102] => cat 1 subcat 1)

数组([740073] => [740102] => cat 1 subcat 1)

为什么是这样?似乎每当$ position为0时.

Fra*_*nes 7

就个人而言,我会使用array_keys,array_searcharray_splice.通过使用检索密钥列表array_keys,您可以将所有密钥作为以数据键开头的数组中的值获取0.然后array_search,您可以使用查找键的键(如果有意义),它将成为原始数组中键的位置.最后array_splice用于删除该位置之后的任何数组值.

PHP:

$categories = array(
    740073 => 'Leetee Cat 1',
    720102 => 'cat 1 subcat 1',
    730106 => 'subsubcat',
    740107 => 'and another',
    730109 => 'test cat'
);

// Find the position of the key you're looking for.
$position = array_search(720102, array_keys($categories));

// If a position is found, splice the array.
if ($position !== false) {
    array_splice($categories, ($position + 1));
}

var_dump($categories);
Run Code Online (Sandbox Code Playgroud)

输出:

array(2) {
  [0]=>
  string(12) "Leetee Cat 1"
  [1]=>
  string(14) "cat 1 subcat 1"
}
Run Code Online (Sandbox Code Playgroud)