php - 从数组数组中过滤唯一值
问题描述
有没有办法改进这个 php 代码?
<?php
require __DIR__ . '/vendor/autoload.php';
$unique_emails = [];
$big_array_full_of_emails = [
array('skywalker1@dagobah.jedi', 'chewbacca1@wookies.win'),
array('skywalker1@dagobah.jedi', 'chewbacca1@wookies.win'),
array('skywalker2@dagobah.jedi', 'chewbacca2@wookies.win'),
array('skywalker3@dagobah.jedi', 'chewbacca3@wookies.win'),
array('skywalker4@dagobah.jedi', 'chewbacca4@wookies.win'),
array('skywalker5@dagobah.jedi', 'chewbacca5@wookies.win'),
];
foreach ($big_array_full_of_emails as $arr) {
foreach ($arr as $email) {
if (!in_array($email, $unique_emails)) {
$unique_emails[] = $email;
}
}
}
var_dump($unique_emails);
@little_coder - Kris Roofe 发布了我正在寻找的内容的想法。只是寻找可能更有效或更清晰的方法来执行逻辑。
解决方案
你可以做到,Demo
$result = array_unique(array_reduce($big_array_full_of_emails,"array_merge",[]));
你也可以用更有效的方式来做,
$result = [];
array_walk_recursive($big_array_full_of_emails,function($v)use(&$result){$result[$v] = $v;});
如果要使用序列索引,只需添加$result = array_values($result);
推荐阅读
- javascript - 如何在映射中将哈希插入我的 url?
- prolog - 如何分析 Prolog 公式?
- angular - 当拦截器在服务发出值之前运行时,如何在传出请求上设置默认标头
- java - 文件选择器的标题
- ios - 在呈现的 UIViewController 后面的 UIViewController 之间进行 segue 的最佳方法是什么
- mxnet - mkl 版本的 mxnet 似乎没有提供 ndarray
- css - 如何将伪元素前后定位到其父元素的中右和左中?
- java - Eclipse JavaEE (Maven) 项目 WAS 7 迁移到 IntelliJ
- mysql - MYSQL:一个表条目包含第二个表中的匹配条目。任何查询想法
- javascript - 定义简单 ES6 组件类的合适方法是什么?