1

I want to sort elements in an array '$to_sort' with regards to how these elements are sorted in a different array '$sorting_order'.

However, I don't know how to handle the case when the two arrays contain different elements.

$sorting_order[]=[introduction,skills,education,experience]
$to_sort[]=[experience,skills,education]

This is the desired result:

$sorted[]=[skills,education,experience]

**SOLUTION: i got this solution that is,

$sorted = array_intersect($sorting_order, $to_sort);
print_r($sorted);

**

0

1 Answer 1

1

I would approach it this way:

1) flip a around using array_flip(); this will create a map with the string values as the key and an ordinal value as the value.

2) use the map from 1) in usort().

$amap = array_flip($a);
usort($b, function($str1, $str2) use ($amap) {
    $key1 = $amap[$str1]; // decide what to do if the key doesn't exist
    $key2 = $amap[$str2];

    if ($key1 > $key2) {
        return 1;
    } elseif ($key1 == $key2) {
        return 0;
    } else {
        return -1;
    }
});
1
  • it would in that condotion also if array size is different as i mentioned ?? Commented Aug 8, 2012 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.