gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:52:29 25 4
gpt4 key购买 nike

我有一个数组

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 是空的 - 知道我做错了什么吗?

最佳答案

为什么额外的间接级别让事情变得更加困惑?为什么不直接用 usort($objectArray, "sortObjects");usort使用 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);

关于PHP 按两个属性对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51687836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com