php 从逗号分隔值的一维数组中收集唯一值

jhiyze9q  于 2023-06-04  发布在  PHP
关注(0)|答案(2)|浏览(195)
Array
(
[0] => Array
    (
        [0] => abc@test.com
        [1] => qwrt@sometest.com
        [2] => haritha@elitesin.com
    )

[1] => Array
    (
        [0] => Kanishka.Kumarasiri@elitesin.com
        [1] => Haritha@elitesin.com
    )

[2] => Array
    (
        [0] => Kanishka.Kumarasiri@elitesin.com
        [1] => test@elitesin.com
    )

)

我有一个这样的数组,我想从这个数组中获取唯一的值。
但我的代码失败了

for ($i = 0; $i < count($return_arr); $i++) {

$new_value[] = explode(",", $return_arr[$i]);
}

print_r (array_unique($new_value));

它说数组到字符串转换错误
我想数组是这样的得到唯一的电子邮件ID

Array
(
[0] => Array
    (
        [0] => abc@test.com
        [1] => qwrt@sometest.com
        [2] => haritha@elitesin.com
        [3] => Kanishka.Kumarasiri@elitesin.com
        [4] => test@elitesin.com
    )

  )
n9vozmp4

n9vozmp41#

因为你的代码是错误的,你试图分解一些不包含在你的数组中的东西,试试下面的代码:

<?php
$arr = [
    ["abc@test.com", "qwrt@sometest.com", "haritha@elitesin.com"],
    ["Kanishka.Kumarasiri@elitesin.com,Haritha@elitesin.com"],
    ["Kanishka.Kumarasiri@elitesin.com,test@elitesin.com"]
];
$allEmails = array();
foreach($arr as $array){
    foreach($array as $email){
        $allEmails[] = explode(",",$email);
    }
}
$new_value = array();    
foreach($allEmails as $array){
    foreach($array as $email){
        $new_value[] = strtolower($email);
    }
}

print_r (array_unique($new_value));

?>
ulmd4ohb

ulmd4ohb2#

您不需要添加任何更多的循环,只需在每次迭代中通过对explode()的返回值使用spread运算符将一个或多个元素推入结果数组。
如果您的任务需要区分大小写的唯一性,您可以非常简单地将未分解的字符串转换为小写。

$new_value = [];
foreach ($return_arr as $csv) {
    array_push($new_value, ...explode(",", strtolower($csv)));
}
var_export(array_unique($new_value));

这将是唯一值的平面数组。

相关问题