user2718671
user2718671

Reputation: 2976

How to sort an array alphabetically and then give that order to another array?

I got 2 Arrays. First one looks like this:

array(33) {
  [0]=>
  string(21) "sourcefile,ending_pdf"
  [1]=>
  string(43) "generated_pdf_preview,ending_reviewpdf"
  [2]=>
  string(37) "generated_jpeg_preview_000,ending_jpg"
  [3]=>
  string(37) "generated_jpeg_preview_001,ending_jpg"
  [4]=>
  string(37) "generated_jpeg_preview_010,ending_jpg"
  ...
}

and the other one looks like this:

array(33) {
  [0]=>
  string(172) "http://my_link/sourcefile.pdf"
  [1]=>
  string(141) "http://my_link/previewpdf"
  [2]=>
  string(149) "http://my_link/my_pdf_file_as_image483568346-0.jpg"
  [3]=>
  string(149) "http://my_link/my_pdf_file_as_image4768746-1.jpg"
  [4]=>
  string(150) "http://my_link/my_pdf_file_as_image6867746-10.jpg"
  [5]=>
  string(150) "http://my_link/my_pdf_file_as_image6867746--11.jpg"
  ...
}

As you can see it is possible to sort the first array but not the second because of the single digits. With asort($first_array) I got the correct order for that array. But I need the same order for my second array. How could I do this? array_multisort($first_array, $asorted_second_array); didnt work so far. Any tips maybe?

Regards

Upvotes: 2

Views: 84

Answers (2)

Alma Do
Alma Do

Reputation: 37365

Since you're going to set order in second array exactly as it will be in first array, I assume both arrays has equal count of elements. Therefore, you can use:

//array that can be (and will be) sorted
$one    = ['rpq','aab', 'rdm', 'llc'];
//array, which order must become same as order of first array
$two    = ['11', '2', '13', '0']; 
$result = array_combine($two, $one);
asort($result);
$result = array_keys($result); //[2, 0, 13, 11] 

Upvotes: 2

exussum
exussum

Reputation: 18576

Close but you dont pass a sorted array to array_multisort

array_multisort($first_array, $second_array, SORT_ASC);

should be ok

array multi sorts changes order based on the sorting, so when you pass it a sorted array, it doesnt need to change the order because its already sorted

Upvotes: 1

Related Questions