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

南笙酒味 提交于 2019-12-01 08:15:54

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

Try this

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

    $newcats[$cat_id] = $cat;
}

$category = $newcats;

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