简体   繁体   English

如何在没有数组函数的情况下从 arrays 获得 output 唯一值?

[英]How to output unique values from arrays without array functions?

I need to output unique values from two arrays, but I can't use any array functions only foreach and if statement.我需要来自两个 arrays 的 output 唯一值,但我不能仅使用 foreach 和 if 语句的任何数组函数。 As result should return one array with unique values and the converted to string.结果应该返回一个具有唯一值的数组并转换为字符串。

I tried to equal two values but output is not I excepted.我试图等于两个值,但 output 不是我例外。

function uniqueNames(array $array1, array $array2){
    $output = [];
    foreach($array1 as $name1) {
        foreach($array2 as $name2) {
            if ($name1 !== $name2){
                $output[] = $name1." ";
            } 
        }
    }
    return implode(",", $output);
}

print_r(uniqueNames(['July', 'Ringold'], ['Harison', 'July', 'Antony']));```

My expected results are July, Ringold, Harison, Antony
But I get July ,July ,Ringold ,Ringold ,Ringold

The problem is that you are comparing each item against every item in the next array and adding the value from the first array for each item that doesn't match.问题是您正在将每个项目与下一个数组中的每个项目进行比较,并为每个不匹配的项目添加第一个数组中的值。

This solution uses the fact that all keys for an array are unique, so first it loops over all of the arrays and adds them into a cumulative array ( $unique ) and then loops over this and gets all of the key values as the list of unique values ( $output )...该解决方案利用了数组的所有键都是唯一的这一事实,因此首先它遍历所有 arrays 并将它们添加到累积数组( $unique )中,然后循环遍历并获取所有键值作为唯一值( $output )...

function uniqueNames(array $array1, array $array2){
    $unique = [];
    $output = [];
    foreach([$array1, $array2] as $sub) {
        foreach($sub as $name2) {
            $unique[$name2] = null;
        }
    }
    foreach ( $unique as $key => $value )   {
        $output[] = $key;
    }
    return implode(",", $output);
}

Alternatively using if , what you have to do is loop over the one array and then check against the all of the elements in the other array.或者使用if ,您要做的就是遍历一个数组,然后检查另一个数组中的所有元素。 Only when you can't find it can you say it needs to be added.只有当你找不到它时,你才能说它需要添加。 This just uses a flag which is changed when the item is found....这仅使用一个标志,该标志在找到该项目时更改....

function uniqueNames(array $array1, array $array2){
    $output = $array1;
    foreach($array2 as $name2) {
        $found = false;
        foreach($array1 as $name1) {
            if ($name1 == $name2){
                $found = true;
                break;
            }
        }
        if (!$found)   {
            $output[] = $name2;
        }
    }
    return implode(",", $output);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM