簡體   English   中英

php - 如何在指定之后刪除數組的所有元素

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

我有一個像這樣的數組:

數組([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 
    }
}

[編輯]第一個答案似乎適用於大多數情況,但不是全部。 如果原始數組中只有兩個項,則只刪除第一個元素,但不刪除后面的元素。 如果只有兩個元素

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

數組([740073] => [740102] => cat 1 subcat 1)

為什么是這樣? 似乎每當$ position為0時。

就個人而言,我會使用array_keysarray_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);

輸出:

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

試試這個

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

    $newcats[$cat_id] = $cat;
}

$category = $newcats;

有幾種方法可以實現這一點,但使用您當前的結構,您可以設置一個標志並刪除標志是否設置...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM