加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

从PHP数组中删除多个元素的有效方法

发布时间:2020-12-13 13:45:54 所属栏目:PHP教程 来源:网络整理
导读:我有一个动态生成的文件名数组,让我们说它看起来像这样: $files = array("a-file","b-file","meta-file-1","meta-file-2","z-file"); 我有几个特定的??文件名,我想从数组中丢弃: $exclude_file_1 = "meta-file-1";$exclude_file_2 = "meta-file-2"; 所以,
我有一个动态生成的文件名数组,让我们说它看起来像这样:
$files = array("a-file","b-file","meta-file-1","meta-file-2","z-file");

我有几个特定的??文件名,我想从数组中丢弃:

$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";

所以,我总是知道我想要丢弃的元素的值,而不是键.

目前我正在考虑几种方法来做到这一点.
一种方法,使用array_filter和自定义函数:

function excludefiles($v)
        {
        if ($v === $GLOBALS['exclude_file_1'] || $v === $GLOBALS['exclude_file_2'])
          {
          return false;
          }
        return true;
        }

$files = array_values(array_filter($files,"excludefiles"));

另一种方式,using array_keys and unset:

$exclude_files_keys = array(array_search($exclude_file_1,$files),array_search($exclude_file_2,$files));
foreach ($exclude_files_keys as $exclude_files_key)
    {    
    unset($files[$exclude_files_key]);
    }
$files = array_values($page_file_paths);

两种方式都能产生预期的效果.

我只是想知道哪一个更有效(以及为什么)?

或许还有另一种更有效的方法可以做到这一点?

也许有一种方法可以在array_search函数中有多个搜索值?

你应该简单地使用 array_diff
$files = array("a-file","z-file");
$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";

$exclude = array($exclude_file_1,$exclude_file_2);
$filtered = array_diff($files,$exclude);

关于PHP的一个坏处是它有数以万计的函数来执行特定的小事情,但有时也会变得方便.

当你遇到这样的情况时(你找到了一个找到相关功能后的解决方案,但你不确定是否有更好的东西),最好在php.net上闲暇浏览功能列表边栏.只需阅读功能名称即可获得丰厚的回报.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读