February 27, 2013

Sorting of some strings?

Question by user1934039

I can only imagine that this is fairly simple, and yet the solution eludes me.

Let assume I have the following variables:

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

I want the groups listed with the highest amount first e.g.:

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.

Perhaps it would be easier to list all the data in a double-array and then sort it?

Answer by Starx

Put your groups in an array

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

var_dump($sorted_groups);

To print the array in your format use the following function

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

Sorting of some strings?

Question by user1934039

I can only imagine that this is fairly simple, and yet the solution eludes me.

Let assume I have the following variables:

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

I want the groups listed with the highest amount first e.g.:

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.

Perhaps it would be easier to list all the data in a double-array and then sort it?

Answer by Starx

Put your groups in an array

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

var_dump($sorted_groups);

To print the array in your format use the following function

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!