Connecting Tech Pros Worldwide Forums | Help | Site Map

Sorting an array

Familiar Sight
 
Join Date: Nov 2006
Posts: 161
#1: Apr 10 '09
If I have

$array1=array(3,7,12,56,89);
$array2=array(12,89,3,7,56);

Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(12,89,3,7,56);

Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,949
#2: Apr 10 '09

re: Sorting an array


Quote:

Originally Posted by beary View Post

If I have

$array1=array(3,7,12,56,89);
$array2=array(12,89,3,7,56);

Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(12,89,3,7,56);

Could you explain why? It seems to me you want 2 arrays with exactly the same content.. which seems slightly wasteful.
Familiar Sight
 
Join Date: Nov 2006
Posts: 161
#3: Apr 10 '09

re: Sorting an array


Quote:

Originally Posted by Markus View Post

Could you explain why? It seems to me you want 2 arrays with exactly the same content.. which seems slightly wasteful.

Sure Markus,

array1 is an array of files
I have then had to do some mapping to get the correct order to display each of the files.
After that mapping, it turns out the correct order is the order of array2.
I can't just "refill" array1 with the actual files, so I need to sort array1 in the order of array2 before I display them. (There is no "natural" order to array2's files; it's not like they're alphabetically ordered or anything - that would make it easy)

Does this make sense?

I'm sure php can somehow do it. I have spent a number of hours on this, but have not had any success yet, and I decided it was time to get some more knowledgable people to help me :)
Expert
 
Join Date: Apr 2006
Posts: 512
#4: Apr 11 '09

re: Sorting an array


Quote:

Originally Posted by beary View Post

If I have

$array1=array(3,7,12,56,89);
$array2=array(12,89,3,7,56);

Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(12,89,3,7,56);

you can just assign array1 the values of array2
Expand|Select|Wrap|Line Numbers
  1. $array1=array(3,7,12,56,89);
  2. print_r($array1);
  3. $array2=array(12,89,3,7,56);
  4. print_r($array2);
  5. $array1=$array2;
  6. print_r($array1);
  7.  
Familiar Sight
 
Join Date: Nov 2006
Posts: 161
#5: Apr 13 '09

re: Sorting an array


Quote:

Originally Posted by ghostdog74 View Post

you can just assign array1 the values of array2

Thanks ghostdog,

I wish it were that easy... I already tried that. It breaks the whole thing. I think it's because the numbers are actually files. So I have this array of files that I need to sort, and so just making array1 (the files) = array2( the numbers representing the files) replaces files with numbers and it breaks. I really do need to be able to sort the original array1.
Reply