PHP从数组中删除特定项

时间:2016-04-09 13:53:31

标签: php arrays

我有一个像2016-04-09 21:15:17 [scrapy] INFO: Scrapy 1.1.0rc1 started (bot: doub) 2016-04-09 21:15:17 [scrapy] INFO: Overridden settings: {'BOT_NAME': 'doub', 'SPIDER_MODULES': ['doub.spiders'], 'NEWSPIDER_MODULE': 'doub.spiders', 'ROBOTSTXT_OBEY': True} 2016-04-09 21:15:18 [scrapy] INFO: Enabled extensions: ['scrapy.extensions.logstats.LogStats', 'scrapy.extensions.corestats.CoreStats'] Unhandled error in Deferred: 2016-04-09 21:15:18 [twisted] CRITICAL: Unhandled error in Deferred: Traceback (most recent call last): File "d:\python\python35-32\lib\site-packages\scrapy\commands\crawl.py", line 57, in run self.crawler_process.crawl(spname, **opts.spargs) File "d:\python\python35-32\lib\site-packages\scrapy\crawler.py", line 152, in crawl return self._crawl(crawler, *args, **kwargs) File "d:\python\python35-32\lib\site-packages\scrapy\crawler.py", line 156, in _crawl d = crawler.crawl(*args, **kwargs) File "d:\python\python35-32\lib\site-packages\twisted\internet\defer.py", line 1274, in unwindGenerator return _inlineCallbacks(None, gen, Deferred()) --- <exception caught here> --- File "d:\python\python35-32\lib\site-packages\twisted\internet\defer.py", line 1126, in _inlineCallbacks result = result.throwExceptionIntoGenerator(g) File "d:\python\python35-32\lib\site-packages\twisted\python\failure.py", line 389, in throwExceptionIntoGenerator return g.throw(self.type, self.value, self.tb) File "d:\python\python35-32\lib\site-packages\scrapy\crawler.py", line 80, in crawl yield exc builtins.ImportError: cannot import name '_win32stdio' 2016-04-09 21:15:18 [twisted] CRITICAL:

这样的数组

使用[312, 401, 1599, 3]我可以删除一个值,在我的示例中,我删除了值401。

但如果我有这个:[312,401,401,401,1599,3],如何只删除一次值401?

如果我删除第一个或最后一个值并不重要,我只需删除ONE 401值,如果我想删除所有401值,我必须删除三次。

谢谢!

3 个答案:

答案 0 :(得分:9)

使用array_search,您可以获取给定值的第一个匹配键,然后您可以使用unset将其删除。

if (false !== $key = array_search(401, $array)) {
  unset($array[$key]);
}

答案 1 :(得分:1)

使用array_intersect,您可以一次检索所有匹配的密钥,这样您就可以决定使用unset删除哪一个特定的密钥。

答案 2 :(得分:1)

搜索特定密钥并将其删除:

if (($key = array_search(401, $array)) !== false) {
   unset($array[$key]); 
}

Man PHP:

array_search

unset