我有一个这样的数组:
Array ( [740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 [730106] => subsubcat [740107] => and another [730109] => test cat )
我想删除数组中键为“720102”的元素之后的所有元素。所以数组会变成:
Array ( [740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 )
我将如何实现这一目标?到目前为止我只有 belw...
foreach ($category as $cat_id => $cat){
if ($cat_id == $cat_parent_id){
//remove this element in array and all elements that come after it
}
}
[编辑] 第一个答案似乎在大多数情况下都有效,但并非全部。如果原始数组中只有两项,它只删除第一个元素而不删除后面的元素。如果只有两个元素
Array ( [740073] => Leetee Cat 1 [740102] => cat 1 subcat 1 )
成为
Array ( [740073] => [740102] => cat 1 subcat 1 )
这是为什么?似乎只要 $position 为 0。
最佳答案
就我个人而言,我会使用 array_keys
, array_search
, 和 array_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"
}
关于php - 如何在指定的一个之后删除数组的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8084136/