【问题标题】:Loop through array of values and sort循环遍历值数组并排序
【发布时间】:2021-12-17 11:13:35
【问题描述】:

我希望你能帮助我使用 PHP 中的一种算法,该算法可以遍历一组值,对它们进行排序并打印非重复项。

这是我写的代码。我想只用循环和 if else 语句来做。我将不胜感激实现这一目标的任何帮助。谢谢


    $input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];`
    $count_array = count($input_array); // count the array`enter code here`
    for($i = 0; $i < $count_array; $i++){ //loop through the array 1st time
        $check_array = false;
       
        //sort array
        for($j = $i+1; $j < $count_array; $j++){
           
            if($input_array[$i] > $input_array[$j]){
                $non_duplicates = $input_array[$i];
                $input_array[$i] = $input_array[$j];
                $input_array[$j] = $non_duplicates;
                    
            }
    
            else if($input_array[$i] == $input_array[$j] &&( $i != $j)){ 
                $check_array = true;
                break;
            }
    
            else{
                $input_array[$i] != $input_array[$j];
            }
    
        }  
    
         if(!$check_array){
            echo($input_array[$i]. ', ');
         }   
        
    }

【问题讨论】:

  • 为什么不使用 array_unique() ?
  • 我想在不使用内置数组函数的情况下做到这一点。如果我使用它,我可以很容易地得到答案

标签: php for-loop if-statement


【解决方案1】:

您可以使用 2 个for 循环来完成,其中第一个循环用于第一个元素,第二个循环始终位于下一个位置,这将有助于始终检查第一个数字是否小于第二个。您创建一个临时变量,在其中存储第一个数字的值,然后将第二个数字的值传递给第一个数字的变量,稍后将存储的临时变量传递给第二个数字的变量(有了这个,你必须将一个的值反转为另一个)。

因为这是对它们进行排序,所以稍后会生成一个 if 来验证它们是否相等,如果相等,则会生成 unset() 以消除数组中的数据。

// Array of values
$input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];
// count the length of array
$count = count($input_array);
// order array and remove duplicates
for ($i = 0; $i < $count; $i++) {
    for ($j = $i + 1; $j < $count; $j++) {
        // order array
        if ($input_array[$i] < $input_array[$j]) {
            $temp = $input_array[$i];
            $input_array[$i] = $input_array[$j];
            $input_array[$j] = $temp;
        }
        // delete duplicates
        if ($input_array[$i] == $input_array[$j]) {
            unset($input_array[$j]);
        }
    }
}
// Return an array with elements in reverse order
$input_array = array_reverse($input_array);

你会得到这样的东西:

 Dump => array(9) {
  [0] => int(1)
  [1] => int(2)
  [2] => int(3)
  [3] => int(4)
  [4] => int(7)
  [5] => int(5)
  [6] => int(8)
  [7] => int(9)
  [8] => int(12)
}

【讨论】:

  • 我实际上希望它在不使用内置函数的情况下对数组进行排序并打印出不重复的值。所以根据数组的输出应该是[1, 2, 4, 12];
猜你喜欢
  • 2017-05-21
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多