zamil
zamil

Reputation: 1930

php usort with multi dimensinal array based on another array

I am following this thread How can I sort arrays and data in PHP?

I want to sort a two dimensinal array based on another single dimensional array

array i want to sort

$main = array(array('name' => 'terry', 'age' => '25', 'sex' => 'm', 'status' => 'active'),
        array('name' => 'raul', 'age' => '26', 'sex' => 'm', 'status' => 'active'),
        array('name' => 'mata', 'age' => '27', 'sex' => 'm', 'status' => 'active'),
        array('name' => 'ronaldo', 'age' => '28', 'sex' => 'm', 'status' => 'active'),
        array('name' => 'drogba', 'age' => '29', 'sex' => 'm', 'status' => 'active'),
        array('name' => 'messi', 'age' => '30', 'sex' => 'm', 'status' => 'active'));

order array

$order = array('30','25');

function cmp(array $a, array $b) {
    global $order;

    return array_search($a['age'], $order) - array_search($b['age'], $order);
}
usort($main, 'cmp');

This is the function i am trying out. but it is not sorting the array.

desired output: I want to get the arrays with age value 30 & 25 as the first two arrays in my input two dimensional array

I am able to do it with this code

function cmp(array $a, array $b) {
    global $order;
   foreach ($order as $ord) {
        if (in_array($ord, $a)) {
        return true;
    }
    }
}

But i want to avoid the foreach loop

Upvotes: 1

Views: 75

Answers (1)

Alexander
Alexander

Reputation: 809

Try this:

$inArray = array(30, 25);
uasort($main, function($a, $b) use ($inArray){ 
    $aAge = $a['age'];
    $bAge = $b['age'];
    $aWeight = 0;
    $bWeight = 0;
    if (in_array($aAge, $inArray)) 
        $aWeight++;

    if (in_array($bAge, $inArray)) 
        $bWeight++;

    if ($aWeight != $bWeight) {
        return $aWeight > $bWeight ? -1 : 1;
    } else if ($aWeight > 0) {
        // need to sort by order which specified in array
        $aIndex = array_search($aAge, $inArray);
        $bIndex = array_search($bAge, $inArray);
        return ($aIndex == $bIndex ? 0 : ($aIndex > $bIndex ? 1 : -1));
    } else {
        // just compare age values
        return ($aAge == $bAge ? 0 : ($aAge > $bAge ? 1 : -1));
    }
});

Upvotes: 1

Related Questions