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


You can also use a function uasort()

like

uasort($Array2, function($a,$b) use (&$Array1){
    foreach($Array1 as $key => $value){
        if($a == $value){
            return 0;
            break;
        }
        if($b == $value){
            return 1;
            break;
        }
    }
    if($a == $b){ return 0;}  return ($a < $b) ? -1 : 1;
});

      



Fiddle

+1


source


Apart from the excellent splash answer, this also works: -

 $Sorted_Array = array_merge(
        array_intersect($Array1, $Array2), 
        array_diff($Array2, $Array1)
 );

      

0


source







All Articles