Jump to content

Easy Sort?


xProteuSx

Recommended Posts

Is there a simple way of sorting data like this?

 

$string = "

50|1|0|15|1|1~

13|2|0|15|1|1~

50|3|0|15|1|0~

19|1|2|10|0|0~

19|2|2|10|0|0~

22|4|2|10|0|0~

22|3|2|10|0|0~

19|5|2|10|0|0~

1|6|2|10|1|0~

19|6|1|10|1|1

";

 

I treat this data as a string, and create an array out of it as follows:

 

$individuals = explode("~", $string);

 

Then I can divide up each individual as follows:

 

foreach ($individuals as $individual)

  {

  $individual = explode("|", $individual);

  }

 

How can I write something that sorts this data by $individual[0], $individual[1], and $individual[2], respectively and in that order??  After sorting I should get the following:

 

 

$string = "

1|2|10|0|0~

13|2|0|15|1|1~

19|2|1|10|0|0~

19|5|2|10|0|0~

19|6|1|10|1|0~|

19|6|2|10|1|1~

22|3|2|10|0|0~

22|4|2|10|0|0~

50|1|0|15|1|1~

50|3|0|15|1|0

";

 

Help?  I have no idea how to write such a function.  Thank you guys.

Link to comment
https://forums.phpfreaks.com/topic/252278-easy-sort/
Share on other sites

I think that the problem with this method is that something like this

 

13|2|0|15|1|1~

5|1|0|15|1|1~

 

will always sort the 13... ahead of the 5... because its treating the substrings as text, whereas they are numerical values divided by the '|' character.

 

Therefore, these substrings should sort as follows

 

5|1|0|15|1|1~

13|2|0|15|1|1~

 

on the basis that the first integer of each substring is sorted by first, hence 5 should be before 13.

Link to comment
https://forums.phpfreaks.com/topic/252278-easy-sort/#findComment-1293359
Share on other sites

find a way to add a zero to the single digit integers before sorting them. problem solved

 

heres a simple function that i use to do it:

function add_nulls($int, $cnt=2) {
    $int = intval($int);
    for($i=0; $i<($cnt-strlen($int)); $i++)
        $nulls .= '0';
    return $nulls.$int;
}

Link to comment
https://forums.phpfreaks.com/topic/252278-easy-sort/#findComment-1293361
Share on other sites

You would use usort -

<?php
$individuals = explode("~", $string);

function cmp($a,$b){
// compare first three elements of each string x|y|z|...
$a = explode('|',$a); // convert the first three elements into a number that can be compared by magnitude
$aa = 100* $a[0] + 10 * $a[1] + $a[2];
$b = explode('|',$b); // convert the first three elements into a number that can be compared by magnitude
$bb = 100* $b[0] + 10 * $b[1] + $b[2];
if ($aa == $bb) {
	return 0;
}
return ($aa < $bb) ? -1 : 1;
}

usort($individuals, "cmp");

 

Link to comment
https://forums.phpfreaks.com/topic/252278-easy-sort/#findComment-1293362
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.