gregpress
gregpress

Reputation: 143

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!

Upvotes: 0

Views: 89

Answers (2)

splash58
splash58

Reputation: 26153

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

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

You could do this with simple foreach loop.

    $arr1 = array(1,1,3,1,2);
    $arr2 = array(1,3,2,4,5);
    $sortArr=  array(2,1,3);
    $new_arr1 = array();
    $new_arr2 = array();
    foreach($sortArr as $s){
        foreach($arr1 as $key => $value){
            if($s==$value){
                array_push($new_arr1, $value);
                array_push($new_arr2, $arr2[$key]);

            }
        }
    }

$new_arr1 and $new_arr2 is the resulted array.

Upvotes: 1

Related Questions