我必须对一组名为" contents"的对象进行排序,如下所示:
"articles" => array:106 [▼
0 => array:5 [▼
"id" => 467823568
"title" => "my tittle"
"data" => "my data"
"category" => 23
"order" => 2
]
1 => array:5 [▼
"id" => 46782356433
"title" => "my tittle 2"
"data" => "my data 2"
"category" => 25
"order" => 1
]
...
]
订单以2个数组定义,category_o
和order_o
如下所示:
"category_o" => array:21 [▼
0 => 25
1 => 95
2 => 135
3 => 72
4 => 4
5 => 23
6 => 7
7 => 803
...
]
我希望根据属性排序文章" category"使用category_o
数组中指定的自定义顺序,然后按属性" order"进行第二次排序。使用order_o
中指定的其他自定义订单。
要对文章进行排序,我使用uasort
方法:
// Call sort function
uasort($articles, array($this, "sortByCategoryOrder"));
使用我的自定义函数sortByCategoryOrder($left, $right);
:
function sortByCategoryOrder($leftItem, $rightItem){
// Array that contains order
$order = $this->category_o;
// Exchange key with value, so we can access "position by value"
$flipped = array_flip($order);
// Init default value for position
$rightPos = 0;
$leftPos = 0;
// Check if order of current category is present:
// the $category_o array could not have all order
// values of articles
if ( (array_key_exists($leftItem["category"], $flipped)) && (array_key_exists($rightItem["category"], $flipped)) ){
// NO MISSING: the 2 element have order
$leftPos = $flipped[$leftItem["category"]];
$rightPos = $flipped[$rightItem["category"]];
}else if (array_key_exists($leftItem["category"], $flipped)) {
// MISS RIGHT: the right elmenet has not custom order specified!
$leftPos = $flipped[$leftItem["category"]];
$rightPos = $leftPos+1;
}else if (array_key_exists($rightItem["category"], $flipped)){
// MISS LEFT: the left elmenet has not custom order specified!
$rightPos = $flipped[$rightItem["category"]];
$leftPos = $rightPos+1;
}else{
// MISS LEFT AND RIGHT: the 2 articles have no custom order specified!
$rightPos = 99999;
$leftPos = 99999;
}
// Make the comparation
return $leftPos >= $rightPos;
}
我有一个名为sortByOrder($left, $right);
的第二个函数,它按order_o
数组值对文章进行排序。
需要 12秒来排序ca. 2000篇文章。
uasort
真的很慢或我在自定义订单功能中犯了一些错误吗?
感谢
解决方案:
感谢@Ahmad Hajjar,我找到了正确的解决方案。
我写了另一种方法,为每个内容设置新属性category_o
和order_o
,并使用双自然升序和php的方法{{ 1}}。
性能提升,并且当前 2000篇文章从ca.传递 9秒到大约1秒!
我报告了我的新方法,希望它有希望:
array_multisort()
答案 0 :(得分:1)
我认为这是模型设计问题。我会改变我的模型来存储category_o排名以及类别值和order_o排名及其值,然后从你需要的任何数据中获取它们...所以当你从数据库中获取数组时你会得到它像这样
"articles" => array:106 [▼
0 => array:5 [▼
"id" => 467823568
"title" => "my tittle"
"data" => "my data"
"category" => 23
"category_o" => 5
"order" => 2
"order_o" => 1
]
1 => array:5 [▼
"id" => 46782356433
"title" => "my tittle 2"
"data" => "my data 2"
"category" => 25
"category_o" => 0
"order" => 1
"order_o" => 2
]
...
]