php-如何在指定一个数组后删除数组的所有元素 [英] php - how to remove all elements of an array after one specified

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

问题描述

我有一个像这样的数组:

I have an array like so:

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

Array ( [740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 [730106] => subsubcat [740107] => and another [730109] => test cat )

我想删除键为"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:

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

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

我将如何实现?到目前为止,我只有那个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

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

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

成为

Array([740073] => [740102] => cat 1 subcat 1)

Array ( [740073] => [740102] => cat 1 subcat 1 )

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

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

推荐答案

我个人会使用 array_keys array_search

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-如何在指定一个数组后删除数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆