对对象的 PHP 数组进行排序,以便相邻对象不共享特定的属性值



我必须对数组对象(都是同一类(进行排序;每个对象作为CCD_ 1属性,该属性总是存储5个可能的整数值中的1个(为了方便起见,将它们称为1-5(。在这个奇怪的用例中,对象必须在数组中随机排序,唯一的条件是没有两个对象可以按顺序共享相同的type值。

即。如果阵列是:

$objects = [$t_1, $t_1, $t_2, $t_2]

其中$t_1表示type属性为1的对象

那么以下顺序就可以了:

$objects = [$t_1, $t_2, $t_1, $t_2]

但初始状态并非如此。

我目前正在做这样的事情(逐字逐句的代码太过混乱,无法发布,但从逻辑上讲,这与我目前所写的内容完全相同(:

$unsorted = $array_of_objects
$sorted = [];
while ( count( $unsorted ) ) {
// randomly select a remaining unsorted object
$next_index = array_rand( $unsorted );
$next_obj   = $unsorted[ $next_index ];
// as long as the current object's type property doesn't match the type property of the preceding obj, add it to $sorted
if ( !count( $sorted ) or ( $next_obj->type != $sorted[ -1 ]->type ) ) {
array_push( $sorted, $next_obj );
unset( $unsorted[ $next_index ] );
}           
}

但我的直觉是,这是低效的,当然,如果没有排序解决方案,它会永远运行。

寻求如何更好和/或更有力地做到这一点的建议。

@update发现之前的答案不正确。

看看这个代码-https://www.tehplayground.com/CcHyHA54oYhyKmDi您可能需要运行它几次,因为当无法按照我们需要的排序方式对数组进行排序时,它会抛出异常。

最新更新