php - how to remove all elements of an array after one specified

自古美人都是妖i 提交于 2019-12-01 06:33:54

问题


I have an array like so:

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

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 )

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 
    }
}

[EDIT] 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 )

becomes

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

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


回答1:


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

Outputs:

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



回答2:


Try this

$newcats = array();
foreach($category as $cat_id => $cat)
{
    if($cat_id == $cat_parent_id)
        break;

    $newcats[$cat_id] = $cat;
}

$category = $newcats;



回答3:


There are a couple of ways to accomplish this, but using your current structure you could set a flag and delete if the flag is set ...

$delete = false;
foreach($category as $cat_id => $cat){
    if($cat_id == $cat_parent_id || $delete){
        unset($category[$cat_id]);
        $delete = true;
    }
}


来源:https://stackoverflow.com/questions/8084136/php-how-to-remove-all-elements-of-an-array-after-one-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!