PHP通过两个属性对对象数组进行排序

时间:2018-08-04 17:06:26

标签: php sorting object

我有一个数组

Array
(
[0] => stdClass Object
    (
        [tab_option_name_selector] => 2
        [fieldtype] => notes
        [order] => 12
    )

[1] => stdClass Object
    (
        [tab_option_name_selector] => 2
        [fieldtype] => notes
        [order] => 8
    )

[2] => stdClass Object
    (
        [tab_option_name_selector] => 1
        [order] => 2
        [fieldtype] => selectbox
    )

[3] => stdClass Object
    (
        [tab_option_name_selector] => 2
        [order] => 3
        [fieldtype] => selectbox
    )
)

我正在尝试使用此usort函数

function osort(&$array, $props) 
{ 
    if(!is_array($props)) 
        $props = array($props => true); 

    $me = usort($array, function($a, $b) use ($props) { 
        foreach($props as $prop => $ascending) 
        { 
            if($a->$prop != $b->$prop) 
            { 
                if($ascending) 
                    return $a->$prop > $b->$prop ? 1 : -1; 
                else 
                    return $b->$prop > $a->$prop ? 1 : -1; 
            } 
        } 
        return -1; //if all props equal        
    });    
    print_r($props);
    return ($me);
} 


$tab = osort($objectArray, "tab_option_name_selector", "order"); 

因此请按标签排序然后排序。

$ tab为空-任何想法我做错了吗?

2 个答案:

答案 0 :(得分:2)

为什么要增加间接级别并使事情变得更加混乱?为什么不使用具有任何比较器功能的usort($objectArray, "sortObjects");函数直接与sortObjects($a,$b)进行混音:根据输入返回负/ 0 /正数?

如果选项卡不同,则返回它们的比较,如果相同,则返回订单比较,完成了吗?

$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);

答案 1 :(得分:1)

您为什么不使用array_multisorthttp://php.net/manual/de/function.array-multisort.php

$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>";