-1

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

假设我有以下变量:

$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.

也许将所有数据列出在双数组中然后对其进行排序会更容易?

4

6 回答 6

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
于 2013-02-27T10:42:12.617 回答
1

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

如果你的数组是

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

你可以使用arsort函数。

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

PHP 手册中的更多信息

然后使用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...
}
于 2013-02-27T10:38:42.230 回答
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**
于 2013-02-27T10:39:17.507 回答
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++;
}
于 2013-02-27T10:41:50.500 回答
0

是的,使用数组是最好的选择。类似的东西

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

之后,您可以对数组进行排序

于 2013-02-27T10:37:16.307 回答
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;
}
于 2013-02-27T10:38:17.960 回答