如何在指定一个数组后删除数组的所有元素

如何在指定一个数组后删除数组的所有元素

本文介绍了php-如何在指定一个数组后删除数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like so:

我想删除键为"720102"的元素之后的所有数组元素.因此该数组将变为:

I want to remove all elements of the array that come after the element with a key of '720102'. So the array would become:

我将如何实现?到目前为止,我只有那个w ...

How would I achieve this? I only have the belw so far...

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

在大多数情况下,第一个答案似乎有效,但并非全部.如果原始数组中只有两项,它将仅删除第一个元素,而不会删除其后的元素.如果只有两个元素

The 1st answer seems to work in most cases but not all. If there are only two items in the original array, it only removes the first element but not the element after it. If there are only two elements

成为

这是为什么?似乎是在$ position为0的时候.

Why is this? It seems to be whenever $position is 0.

推荐答案

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

Personally, I would use array_keys, array_search, and array_splice. By retrieving a list of keys using array_keys, you get all of the keys as values in an array that starts with a key of 0. You then use array_search to find the key's key (if that makes any sense) which will become the position of the key in the original array. Finally array_splice is used to remove any of the array values that are after that position.

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);

输出:

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

这篇关于php-如何在指定一个数组后删除数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 12:59