phparraysarray-multisort

Sort two arrays by another in PHP


I have two data arrays, each with the same number of elements. There is also a sorting array that has the values in the first array as unique elements.

The data arrays can have any number of elements but will each have the exact same number of elements.

I am hoping to have both data arrays sorted by the sort array.

Example:

array1(‘group1’,’group1’,’group3’,’group1’,’group2’); (5 elements)

array2(‘data1’,’data3’,’data2’,’data4’,’data5’); (5 elements)

sortArray(‘group2’,’group1’,’group3’);(3 elements, no particular order, one each from array1)

The result would be:

array(‘group2’,’group1’,’group1’,’group1’,’group3’);

array(‘data5’,’data1’,’data3’,’data4’,’data2’);

I tried to get this working with array_multisort, but the solution is evading me.

Thanks for any insight!


Solution

  • make temporary array corresponding to array1 where for each element of array1 is set it's index in array2. And sort all arrays at once

    $array1 = array('group1','group1','group3','group1','group2'); 
    $array2 = array('data1','data3','data2','data4','data5'); 
    $sortArray = array('group2','group1','group3');
    
    $flip = array_flip($sortArray);
    $sort = [];
    foreach($array1 as $x) {
      $sort[] = $flip[$x];      // [1,1,2,1,0]
    }
    array_multisort($sort, $array1, $array2);
    
    print_r($array1);
    print_r($array2);
    

    demo