Reputation: 47
I have two arrays, both have numbers but are extracted in specific order from a database. So what I want to do is to sort one of them in a acceding mode and the second array rearrange it's values to correspond the first one. for instance
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
So in our example I need the first array to become (14,20,30) witch can be made with the sort function but the second also have to become (4,3,2) to correspond with the first array.
Any ideas?
Upvotes: 3
Views: 65
Reputation: 9692
You can use array_combine to use the first array as keys and the second array as values.
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
$Array = array_combine($firstarray, $secondarray);
Output:
Array
(
[14] => 4
[30] => 2
[20] => 3
)
Then sort the keys asc.
ksort($Array);
Output:
Array
(
[14] => 4
[20] => 3
[30] => 2
)
And if you want to have a seperate $secondarray you can do:
$secondarray = array_values($Array);
$secondarray = array_flip($secondarray); // Values are keys now.
Upvotes: 0
Reputation: 254916
You need to use array_multisort
:
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
array_multisort($firstarray, $secondarray);
var_dump($firstarray, $secondarray);
Online demo: http://ideone.com/FyU1cl
Upvotes: 2