PHP sort array of objects by two properties



PHP Snippet 1:

$array = array(
    (object)array(
        'tab_option_name_selector' => 2,
        'fieldtype' => 'notes',
        'order' => 12
    ),
    (object)array(
        'tab_option_name_selector' => 2,
        'fieldtype' => 'notes',
        'order' => 8
    ),
    (object)array(
        'tab_option_name_selector' => 1,
        'order' => 2,
        'fieldtype' => 'selectbox'
    ),
    (object)array(
        'tab_option_name_selector' => 2,
        'order' => 3,
        'fieldtype' => 'selectbox'
    )
);

function compareTabAndOrder($a, $b) {
    // compare the tab option value
    $diff = $a->tab_option_name_selector - $b->tab_option_name_selector;
    // and return it. Unless it's zero, then compare order, instead.
    return ($diff !== 0) ? $diff : $a->order - $b->order;
}

usort($array, "compareTabAndOrder");
print_r($array);

PHP Snippet 2:

$data = //your array

//Create independent arrays
foreach ($data as $row) {
  foreach ($row as $key => $value){
    ${$key}[]  = $value; 
    //Creates $tab_option_name_selector, $fieldtype and $order array
    //in order to use them as independent arrays in array_multisort.
  }  
}

array_multisort($tab_option_name_selector, SORT_ASC, $order, SORT_ASC, $data);

//$data sorted as expected.
echo "<pre>";
print_r($data);
echo "</pre>";