I have two PHP-arrays and i want to sort the first by using the second. for example my first array could be:
[ "Hello" => "Hallo", "World" => "Welt", "PHP" => "PHP", "Symfony" => "Symfony" ]
If my second array now is this:
[ "0" => "2", "1" => "1", "2" => "3", "3" => "0" ]
This second array always has values from 0 to n and no duplicates. I want to sort the first array by the numbers in the second so it should look like that:
[ "Symfony" => "Symfony", "World" => "Welt", "Hello" => "Hallo", "PHP" => "PHP" ]
How can i sort my array like that?
I asked this question before and i got referred to this question, but i can’t make out the solution for my case as i don’t know the keys and values in the first array. It should work for every key, so please don’t just refer me to this question again because i don’t get how this helps me.. Thanks
Advertisement
Answer
<?php $a1 = [ "Hello" => "Hallo", "World" => "Welt", "PHP" => "PHP", "Symfony" => "Symfony", ]; $a2 = [ "0" => "2", "1" => "1", "2" => "3", "3" => "0", ]; //it will rearrange all arrays based on the first array order array_multisort($a2, SORT_ASC, $a1); print_r($a1);
Output:
Array ( [Symfony] => Symfony [World] => Welt [Hello] => Hallo [PHP] => PHP )