在PHP中使用临时变量对数组进行排序

时间:2019-07-04 14:28:40

标签: php

我是一个初学者,我们的教授告诉我们,我们需要解释一下此代码的用途。我知道它是用于排序的,但我想简要解释一下。有人可以帮我吗?

<?php
function descending(){
    $num1 = $_GET['num1'];
    $num2 = $_GET['num2'];
    $num3 = $_GET['num3'];

    if ($num1 < $num2) {
        $temp = $num1;
        $num1 = $num2;
        $num2 = $temp;
    }
    if ($num1 < $num3) {
       $temp = $num1;
       $num1 = $num3;
       $num3 = $temp;
    }
    if ($num2 < $num3) {
       $temp = $num2;
       $num2 = $num3;
       $num3 = $temp;
    }
    echo "<br>";
    echo $num1a . " , " . $num2a . " , " . $num3a;
    echo "<br>";

?>

1 个答案:

答案 0 :(得分:0)

降3个数字的概念是通过将第一个数字与其他两个数字相加而得出的,第一个数字应大于其他数字,因此,如果第二个数字大于交换到第一个数字的第一个数字与第三个数字相同,则将第一个数字与第二个数字进行比较此过程后的第一个数字将大于2。检查剩余的两个变量,然后再次比较,在第二个变量中分配更大的数字。这样,它就递减了。

<?php 
function descending(){
    $num1 = $_GET['num1'];    // Let suppose $num1 = 1
    $num2 = $_GET['num2'];    // Let suppose $num2 = 2
    $num3 = $_GET['num3'];    // Let suppose $num3 = 3


    if ($num1 < $num2) {     // here $num1 (1) is less than $num2(2)
        $temp = $num1;       // $temp(2) 
        $num1 = $num2;       // copy $temp(2) to $num1(2)
        $num2 = $temp;       // this process swap $num1(2) and $num(1)
    }
    if ($num1 < $num3) {     // here $num1(2) and $num3(3) which is less so swap
        $temp = $num1;
        $num1 = $num3;
        $num3 = $temp;       //After swap $num1(3) & $num3(2)      

    }

    //now at this time $num1 greatest among other two variable

    if ($num2 < $num3) {   //$num2(1) and $num3(2) so swap
        $temp = $num2;
        $num2 = $num3;
        $num3 = $temp;     // this way $num2 will be greater
    }

    echo "<br>";
    //first error: After descending value store in $num1, $num2, and $num3
    //not in $num1a, $num2a, and $num3a these variable.
    echo $num1 . " , " . $num2 . " , " . $num3; 
    echo "<br>";
 }  // second error missing this curly bracket.
?>

希望您能理解并忽略我的英语不好。快乐编码:)

相关问题