|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Imagine this:
@NewsID = (1,2,3,4,5); @NewsViews = (28,24,13,67,12); and that $NewsViews[0] is the number of times that $NewsID[0] has been viewed. Now I want to sort them, so that I get an array starting with the lowest view-rate. When I do a @SortedNewsViews=sort(@NewsViews), the array @NewsViews is sorted, but the array @NewsID remains the same. Now $NewsViews[0] is NOT the number of times that $NewsID[0] has been viewed. So how do I sort @NewsViews together with @NewsID? |
|
#2
|
||||
|
||||
|
Hi!
What about using a hash for this? Like Code:
%News = (
1 => 28,
2 => 24,
3 => 13,
[...]
);
This way id and value are tied together and may be sorted at will either by id or by value. Greetings Roland. |
|
#3
|
|||
|
|||
|
I don't quite get it?
If I'd do a @SortedNews = sort(keys(%News)) I'd end up with any array with 13, 24, 28?? |
|
#4
|
|||
|
|||
|
You want to be using a hash for this. That will accomplish what I think it is you are trying to accomplish.
Right now you have no guarantees that the item with ID #1 will have the lowest viewing rate so you can't expect them to correspond when you sort the arrays. Try this: It outputs to STDOUT but I'm sure you can tweak it to drop the info into a new hash: Code:
%News = (
1 => 28,
2 => 24,
3 => 13,
4 => 67,
5 => 12,
);
foreach $key ( sort { $News{$a} <=> $News{$b} } keys %News ) {
print $News{$key}, "\t$key\n";
}
__________________
- dsb - ![]() Perl Guy |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > sorting 2 arrays |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|