首页 > 解决方案 > 从数组数组中过滤唯一值

问题描述

有没有办法改进这个 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 发​​布了我正在寻找的内容的想法。只是寻找可能更有效或更清晰的方法来执行逻辑。

标签: php

解决方案


你可以做到,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);


推荐阅读