Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 数组_unique()的自身实现_Php_Arrays - Fatal编程技术网

Php 数组_unique()的自身实现

Php 数组_unique()的自身实现,php,arrays,Php,Arrays,我有这个阵列: $number = array("a", "b", "b", "c", "a", "b", "c", "b", "c"); 现在我想得到所有唯一的值。表示结果应为: $result = array("a", "b", "c"); 现在我知道,使用array_unique可以很容易地解决这个问题。但是我想用for循环、unset和array\u值来编写我自己的array\u unique小实现。使用array\u unique <?php $number=arra

我有这个阵列:

$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
现在我想得到所有唯一的值。表示结果应为:

$result = array("a", "b", "c");
现在我知道,使用array_unique可以很容易地解决这个问题。但是我想用for循环、unset和array\u值来编写我自己的array\u unique小实现。

使用array\u unique

<?php
    $number=array("a","b","b","c","a","b","c","b","c");
    $unique_array=array_unique($number);
    print_r($unique_array);
?>

也许是这样的?在这里,我们循环通过和数组,从一个位置0开始,从另一个位置1开始。我们将$i位置与数组中的所有其他位置进行比较,如果它找到两个相同的位置,则删除第二个位置

<?php
    $number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
    $count = count($number);

    for($i = 0; $i < $count; $i++) {
        for($j = $i+1; $j < $count; $j++) {
            if(isset($number[$j]) && isset($number[$i]) && $number[$i] == $number[$j]) {
                unset($number[$j]);
            }
        }
    }

    print_r($number);

就用吧。我不知道你怎么会花三个小时在这个问题上,而谷歌的快速搜索可以在几分钟内解决这个问题。为什么不使用呢?你必须使用这些功能,或者你可以使用另一个功能?这可以很容易地解决。我知道。但我想使用for、unset和array_值。如果你有这样的逻辑。让我知道。为什么你要把你的代码变得复杂!!你必须使用数组_unique吗?您能告诉我如何使用for、unset和array_值消除这些重复项吗?请给我几分钟时间,我愿意在这段代码中比较相同的数组,如$number[0]==$number[0]。你能避免吗?现在检查一下,我已经更新了我的答案。就像那样。现在我正在努力理解它。谢谢。我已经添加了一个解决方案的小说明。顺便说一句,你需要多少分钟来解决这个问题?几分钟,因为我在想为什么你需要数组_值。我之所以有这种逻辑,是因为我使用的是C语言,它没有像array\u unique、array\u search等很酷的功能
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$count=count($number);
for($i=0;$i<$count;$i++)
{
    if($i<count($number))
    {
        for($j=$i+1;$j<$count;$j++)
        {
            if($number[$i]==$number[$j])
            {
                unset($number[$j]);
             }
        }

    }
}
$number=array_values($number);
print_r($number);
Array ( [0] => a [1] => b [2] => c ) 
<?php
    $number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
    $count = count($number);

    for($i = 0; $i < $count; $i++) {
        for($j = $i+1; $j < $count; $j++) {
            if(isset($number[$j]) && isset($number[$i]) && $number[$i] == $number[$j]) {
                unset($number[$j]);
            }
        }
    }

    print_r($number);