dongshi4773 2014-03-12 23:57
浏览 50
已采纳

php从大到小,反之亦然

I am new to php and I am doing this assignment that I am only supposed to do the missing code of the whole code using for loop. Can any one please help me what I am missing? Thank you in advance! Hoping my for loop works fine, the output I am getting is:

Order in the beginning: 4,7,-2,0,6
Largest to smallest: Array
Smallest to largest: Array

Instead was supposed to be for example:

Order in the beginning: 4,7,-2,0,6
Largest to smallest: 7,6,4,0,-2
Smallest to largest: -2,0,4,6,7

Assignment:

Complete the following PHP script so that it prints the numbers, given in a form, in a specific order. The script should organize the numbers from largest to the smallest and from smallest to largest and print both of these number strings on screen. The points are sent to the script as a character string, where points are separated with comma (e.g. 4,5,2). Points are divided into an array with the explode-function. Using the sort-function is not allowed. Do the organizing with a for-statement. Incomplete program:

<?php

    $numberstring = $_GET['numberstring'];

    $array = explode(',',$numberstring);



    echo "Order in the beginning: $numberstring
";



    // Your code here and only here



    echo "Largest to smallest: $largest_smallest
";

    echo "Smallest to largest: $smallest_largest
";

?>

My code which arranges the input in descending and descending order:

for ($j = 0; $j < count($array); $j++) {
    for ($i = 0; $i < count($array) - 1; $i++) {
        if ($array[$i] > $array[$i + 1]) {
            $temp = $array[$i + 1];
            $array[$i + 1] = $array[$i];
            $array[$i] = $temp;

        }

    }
 $largest_smallest=$array;  
}


for ($j = 0; $j < count($array); $j++) {
    for ($i = 0; $i < count($array) - 1; $i++) {
        if ($array[$i] < $array[$i + 1]) {
            $temp = $array[$i + 1];
            $array[$i + 1] = $array[$i];
            $array[$i] = $temp;

        }
    }
    $smallest_largest=$array;
}
  • 写回答

1条回答 默认 最新

  • dongming8867 2014-03-13 00:08
    关注

    Basically, you see Array because you can't print an array like you would a string. If you want the output in the same form as the input, comma separated, you'll need to use a function to do so. If explode turns a string into an array by splitting it on a delimiter, could you think of a name for a function that does the opposite? The hint is in the name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!