在一个数组中取消一定范围内的键

4

如何在类似这样的数组中取消70到80之间的一系列键?

[63] => Computer Science and Informatics
[64] => Dentistry
[65] => Development Studies
[66] => Drama, Dance and Performing Arts
[67] => Earth Systems and Environmental Sciences
[68] => Economics and Econometrics
[69] => Education
[70] => Electrical and Electronic Engineering
[71] => English Language and Literature
[72] => Epidemiology and Public Health
[73] => European Studies
[74] => French
[75] => General Engineering and Mineral & Mining Engineering
[76] => Geography and Environmental Studies
[77] => Geography and Environmental Studies
[78] => German, Dutch and Scandinavian Languages
[79] => Health Services Research
[80] => History
[81] => History of Art, Architecture and Design
[82] => Iberian and Latin American Languages
[83] => Infection and Immunology
[84] => Italian
[85] => Law
[86] => Library and Information Management
[87] => Linguistics
[88] => Mechanical, Aeronautical and Manufacturing Engineering
[89] => Metallurgy and Materials
[90] => Middle Eastern and African Studies

需要移除 67 个键,所以不想逐个取消每个键。 - smith
2个回答

11
你可以尝试使用array_slice
$return = array_slice($original, 0, 60)

然后

$return = $return+array_slice($original, 70)

或者

array_splice

$return = array_splice($original, 60, 10)

3
这个方法虽然可行,但效率很低。除了最初的数组外,你还要创建3个额外的数组。 - ryeguy
考虑到这是一个相当小的数据集,我可能会选择这个解决方案,因为我不认为它的效率会对性能产生任何明显的影响,而且它易读且有些优雅。点赞。 - karim79

10

这真的没有捷径:

for ($i = 70; $i <= 80; $i++)  
    unset($array[$i]);

+1 对于这个问题也是一个更简单的解决方案,而且可以完成同样的工作。 - Alex Weber
2
有点令人失望的是,所有那些总是问是否有一个能做一些奇特任务的函数的PHP程序员们,其实用for()/foreach()循环就已经足够了。 - TravisO
1
你能在取消时向前遍历数组吗?这样做不会导致移动过程中下一个要取消的元素的索引发生变化吗?我认为你必须从80到70逐步遍历,递减i。 - John Yetter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接