phparrayssortingmultidimensional-array

Sort a 2d array by one column then another


How can I sort an associative array by a weight AND type?

Input

array(
    'a'     => array( 'type' => 't1', 'weight' => 1, 'text' => 'text1' ),
    'b'     => array( 'type' => 't1', 'weight' => 3, 'text' => 'text2' ),
    'c'     => array( 'type' => 't2', 'weight' => 5, 'text' => 'text3' ),
    'd'     => array( 'type' => 't1', 'weight' => 2, 'text' => 'text4' ),
    'e'     => array( 'type' => 't2', 'weight' => 4, 'text' => 'text5' ),
    'f'     => array( 'type' => 't2', 'weight' => 4, 'text' => 'text6' )
);

Desired Output

array(
    'a'     => array( 'type' => 't1', 'weight' => 1, 'text' => 'text1' ),
    'd'     => array( 'type' => 't1', 'weight' => 2, 'text' => 'text4' ),
    'b'     => array( 'type' => 't1', 'weight' => 3, 'text' => 'text2' ),
    'e'     => array( 'type' => 't2', 'weight' => 1, 'text' => 'text5' ),
    'f'     => array( 'type' => 't2', 'weight' => 1, 'text' => 'text6' ),
    'c'     => array( 'type' => 't2', 'weight' => 5, 'text' => 'text3' )
);

Type "t2" must appear at end of array, all other types at start.

Weight must be sorted after type.

I am using uasort with a custom compare function, but am struggling. Here is what I have, but it doesn't work:

function my_comparer($a, $b) {
    return ( $a['type'] !== 't2' && $b['type'] === 't2' )
        ? -1
        : $a['weight'] - $b['weight'];
}

Solution

  • Your function doesn't take account of ($a['type']=='t2')

    function my_comparer($a, $b) {
        if ( ($a['type']==='t2') && ($b['type']!=='t2')) return -1;
        if ( ($b['type']==='t2') && ($a['type']!=='t2')) return 1;
        return ($a['weight'] - $b['weight']);
    }