Sorting an array based on other array values ββin PHP
I have an array with values ββas follows: -
$Array1 = array("myfirst_value", "mysecond_value", "mythird_value"}
Now for my other array, the list happens at random: -
$Array2 = array
(
[4] => myfirst_value
[8] => myforth_value
[21] => mysecond_value
[7] => myfifth_value
[17] => mysixth_value
[20] => mythird_value
[16] => myseventh_value
)
I hope $ Array2 will be sorted based on the order of the values ββin $ Array1.
So, I hope that $ Array2 is sorted and is: -
$Array2 = array
(
[4] => myfirst_value
[21] => mysecond_value
[20] => mythird_value
[7] => myfifth_value
[8] => myforth_value
[16] => myseventh_value
[17] => mysixth_value
)
Note that the values ββof Array1 are sorted first and the rest are simply outputted without any ordering.
thank
+3
source to share
3 answers
If I get you right
$Array1 = array("myfirst_value", "mysecond_value", "mythird_value");
$Array2 = array
(
4 => myfirst_value,
8 => myforth_value,
21 => mysecond_value,
7 => myfifth_value,
17 => mysixth_value,
20 => mythird_value,
16 => myseventh_value
);
// Remove elements of the 1st array from the 2nd
function f ($v) { global $Array1; return in_array($v, $Array1);}
$a1 = array_filter($Array2, 'f');
// Take the rest elements
$a2 = array_diff_key($Array2, $a1);
// Combine back
print_r($a1+$a2);
result
Array
(
[4] => myfirst_value
[21] => mysecond_value
[20] => mythird_value
[8] => myforth_value
[7] => myfifth_value
[17] => mysixth_value
[16] => myseventh_value
)
+1
source to share