Sort an array by the keys of another array

There are 2 arrays with the same length and with the same keys:

$a1 = [1=>2000,65=>1354,103=>1787]; $a2 = [1=>'hello',65=>'hi',103=>'goodevening']; asort($a1); 

The keys a1 and a2 are identifiers from the database.

a1 is sorted by value. After sorting, how can we use the same sort order in a2?

Thanks!

+4
source share
4 answers

I believe this works:

 $a1 = array(1=>2000,65=>1354,103=>1787); $a2 = array(1=>'hello',65=>'hi',103=>'goodevening'); asort($a1); // sort $a1, maintaining array index // sort $a2 by key, using the order of $a1 function my_uksort($a, $b) { global $a1; return $a1[$a] < $a1[$b] ? -1 : 1; } uksort($a2, 'my_uksort'); var_dump($a1); var_dump($a2); 
+5
source

Not optimal, maybe .. but this is short:

 $a1 = array(1=>2000,65=>1354,103=>1787); $a2 = array(1=>'hello',65=>'hi',103=>'goodevening'); asort($a1); foreach(array_keys($a1) as $i) $out[$i] = $a2[$i]; echo join("\n", $out); 

take a look at uasort () also

+1
source

You probably want to look at array_multisort () if you can handle the loss of association of identifiers (arrays will be reindexed).

 array_multisort($a1, $a2); 
0
source
 foreach($a1 as $key => $value){ //do something with $a2 echo $a2[$key]; } 
0
source

Source: https://habr.com/ru/post/1307574/


All Articles