PHP,从下拉列表中排序选项

时间:2013-02-27 11:39:52

标签: php sorting

我的下拉列表有这样的选项

something 4M/512k
something 10M/768k
something 4M/2M
something 10M/5M
something 10M/10M
something 20M/20M (FTTH)
something 60M/60M (FTTH)
something 100M/100M (FTTH)

现在排序应该是这样的:不要看一下单词,排序的第一列应该是4M或10M ... /符号之前的值。之后排序应该继续第二列这是512k或2M ...但它取决于第二列中的值是否包含k char(表示kylobytes)应该是第一个(M表示兆字节)。 第三列应该是FTTH。例如,如果该行包含(FTTH)字,它应该放在最后......

这是它应该是什么样子的例子

something 4M/512k
something 4M/2M
something 10M/768k
something 10M/5M
something 10M/10M
something 20M/20M (FTTH)
something 60M/60M (FTTH)
something 100M/100M (FTTH)

1 个答案:

答案 0 :(得分:0)

您可以使用http://www.php.net/usort创建自己的排序方法,对包含下拉选项的数组进行排序。

这应该会给你一个良好的开端:

<?php
$data[] = "something 4M/512k";
$data[] = "something 10M/768k";
$data[] = "something 4M/2M";
$data[] = "something 10M/5M";
$data[] = "something 10M/10M";
$data[] = "something 20M/20M (FTTH)";
$data[] = "something 60M/60M (FTTH)";
$data[] = "something 100M/100M (FTTH)";

function mysort($a, $b){
  list($something, $a_speed) = explode(" ", $a);
  list($something, $b_speed) = explode(" ", $b);

  list($a_speed_part_1, $a_speed_part_2) = explode("/", $a_speed);
  list($b_speed_part_1, $b_speed_part_2) = explode("/", $b_speed);

  //TODO: add M/k comparison or calculation

  if(intval($a_speed_part_1) > intval($b_speed_part_1)){
    return 1;
  } elseif (intval($a_speed_part_1) < intval($b_speed_part_1)) {
    return -1;
  } else {
    if(intval($a_speed_part_2) > intval($b_speed_part_2)){
      return 1;
    } elseif (intval($a_speed_part_2) < intval($b_speed_part_2)) {
      return -1;
    } else {
      return 0;
    }
    return 0;
  }
}

usort($data, "mysort");
echo "<pre>";
print_r($data);
echo "</pre>";