为什么我的php脚本没有排序数组?

时间:2017-07-26 09:52:45

标签: php arrays sorting

我正在尝试对变量中保存的数据进行排序。我首先将其转换为数组,然后尝试按升序对其进行排序,但似乎无法正常工作。

这是我的代码

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));
$cars = array($cars);

sort($cars, 1);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }

任何解决方法吗?

4 个答案:

答案 0 :(得分:0)

尝试rsort

$str = '"10:A", "11:Q", "12:V"';
    $cars = (explode(",",$str));

    rsort($cars);
    $clength=count($cars);
    for($x=0;$x<$clength;$x++)
      {
      echo $cars[$x];
      echo "<br>";
      }

答案 1 :(得分:0)

如果您想根据号码排序,请尝试以下方法:

<?php
function my_sort($a,$b)
{
  $intval_a = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
  $intval_b = filter_var($b, FILTER_SANITIZE_NUMBER_INT);
  if(intval($intval_a) > intval($intval_b))
    return 1;
}
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = explode(',',$str);
$cars = ($cars);

usort($cars, "my_sort");
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
  echo $cars[$x];
  echo "<br>";
}

答案 2 :(得分:0)

我注意到了一些事情。首先,你爆炸了产生数组的字符串。然后,您将该数组放入另一个数组并尝试对其进行排序。您应该删除第$cars = array($cars);

我还建议在尝试对字符串进行排序之前从字符串中删除引号和空格,例如,您要对10:A而不是"10:A"进行排序。

另一件事是sort函数应该将一个标志作为第二个参数来定义要执行的排序类型。有关您可用的不同标志,请参阅docs。我猜你想把它分类

  

1:A,2:X,3:C ......

而不是

  

1:A,10:A,11:Q ...

在这种情况下,您应该使用SORT_NATURAL标志。 (或者,您可以使用natsort function)。

这些更改将提供以下代码:

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$str = str_replace(array('"', ' '), '', $str);
$cars = explode(",",$str);

sort($cars, SORT_NATURAL);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
    echo $cars[$x];
    echo "<br>";
}

答案 3 :(得分:0)

使用natsort()函数

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));

natsort($cars);
echo "<pre>"; print_r($cars);
foreach($cars as $car)
{
    echo $car."<br>";
}

Check here

希望这会有所帮助。