排序一些字符串?

时间:2013-02-27 10:34:56

标签: php

我只能想象这很简单,但解决方案却让我望而却步。

假设我有以下变量:

$group1 = "5";
$group2 = "1";
$group3 = "15";
$group4 = "3";
$group5 = "7";
$group6 = "1";
$group7 = "55";
$group8 = "0";
$group9 = "35";

我希望列出最高金额的群组首先例如:

Group 7 is number 1 with 55.
Group 9 is number 2 with 35.
Group 3 is number 3 with 15.
Group 5 is number 4 with 7.
Group 1 is number 5 with 5.
Group 4 is number 6 with 3.
Group 2 is number 7 with 1.
Group 6 is number 8 with 1.
Group 8 is number 9 with 0.

也许将双列中的所有数据列出然后排序会更容易吗?

6 个答案:

答案 0 :(得分:1)

首先,使用数组(只是常用的数组)。

如果您的数组是

$group = array(1 => 5, 2 => 1 ... )

您可以使用arsort功能。

这里我使用数字,而不是字符串。如果您将使用字符串(对于值),则需要一个用于排序(SORT_NUMERIC

的标志

PHP Manual

中的更多信息

然后使用foreach

foreach($group as $key => $value){
    $key is number of varaiable
    $value is value of it.
    you also may add counter to print 1,2,3...
}

答案 1 :(得分:1)

为此目的使用数组

$group[1] = "5";
$group[2] = "1";
$group[3] = "15";
$group[4] = "3";
$group[5] = "7";
$group[6] = "1";
$group[7] = "55";
$group[8] = "0";
$group[9] = "35";

然后对其进行排序。

arsort($group, SORT_NUMERIC);   // SORT_NUMERIC suggested by **fab**

答案 2 :(得分:1)

将数据放在关联数组中,并使用关联识别排序对其进行排序:

$groups = array(
'group1' => "5",
'group2' => "1",
'group3' => "15",
'group4' => "3",
'group5' => "7",
'group6' => "1",
'group7' => "55",
'group8' => "0",
'group9' => "35",
);

arsort($groups);

// iteration as usual
foreach ($groups as $group_name => $value) {
}

// getting elements with the array functions based around the array's internal pointer
reset($groups); // reset the pointer to the start
print key($groups); // the first element's key
print current($groups); // the first element's value
next($groups); // moving the array to the next element

答案 3 :(得分:0)

是的,使用阵列是最好的事情。 类似的东西

$group[1]="5";
$group[2]="1";

之后你可以对数组进行排序

答案 4 :(得分:0)

将您的群组放入数组

$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups); //This sort the array is descending order

var_dump($sorted_groups);

要以您的格式打印数组,请使用以下函数

count = 1;
foreach($groups as $key => $value) {
    echo "Group ".($key+1)." is number ".$count++." with ".$value;
}

答案 5 :(得分:0)

执行此操作的最佳方法是使用数组arsort。这将使您的索引保持完整。

arsort返回一个布尔值,因此不要分配给新变量

$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups, SORT_NUMERIC);

$i = 1;

foreach ($groups as $key => $val) {
    echo 'Group ' . $key . ' is number ' . $i . ' with ' . $val;
    $i++;
}