asort asorts instead of sorts :)
Posted: Thu Apr 09, 2009 4:04 am
Hi, please take a look at this code:
This is the output, the first three strings came out reverse sorted
but otherwise (for non equal strings) it works as expected:
Function asort should sort array and maintain indexes. Why the hell is it reverse-sorting already sorted strings? If you change sorting function to sort, it works as expected:
But I need to sort the array and maintain indexes. How should I do this? I have php version 5.2.8. Is that a normal behaviour, or a bug?
My problem:
I have a log file, which starts with date and time, the rest is text string, which should not be sorted. So I divide the log lines into two arrays and sort only the first array with maintainging index. But I found that asort cannot be used, when it reverse sorts already sorted.
Basically, I need to sort the lines up to N-th character (N can be different for each line) and rest of the string on line should be ignored (not compared in sorting).
Please answer:
1. is this some crazy behaviour of asort?
2. what do you suggest to solve my problem?
Thank you and nice day to all.
Code: Select all
<?php
header("Content-Type: text/plain");
$testarray=Array();
$testarray[0]="2009.1.28 08:29:31";
$testarray[1]="2009.1.28 08:29:31";
$testarray[2]="2009.1.28 08:29:31";
$testarray[3]="2009.1.28 08:29:32";
$testarray2=Array();
$testarray2[0]="0";
$testarray2[1]="1";
$testarray2[2]="2";
$testarray2[3]="3";
asort($testarray);
reset($testarray);
while (list ($key, $val) = each ($testarray)) {
echo($val." key=$key ".$testarray2[$key]."\n");
}
?>Code: Select all
2009.1.28 08:29:31 key=2 2
2009.1.28 08:29:31 key=1 1
2009.1.28 08:29:31 key=0 0
2009.1.28 08:29:32 key=3 3Code: Select all
2009.1.28 08:29:31 key=0 0
2009.1.28 08:29:31 key=1 1
2009.1.28 08:29:31 key=2 2
2009.1.28 08:29:32 key=3 3My problem:
I have a log file, which starts with date and time, the rest is text string, which should not be sorted. So I divide the log lines into two arrays and sort only the first array with maintainging index. But I found that asort cannot be used, when it reverse sorts already sorted.
Basically, I need to sort the lines up to N-th character (N can be different for each line) and rest of the string on line should be ignored (not compared in sorting).
Please answer:
1. is this some crazy behaviour of asort?
2. what do you suggest to solve my problem?
Thank you and nice day to all.