2

我有一个键控数组,每个槽包含两条信息:公司名称和优先级。我正在尝试找到一种方法来改组具有相同优先级值的公司名称。我熟悉洗牌功能,但是,我不想洗牌忽略优先级值的数组中的所有元素,我只想洗牌具有相同优先级值的元素。

这是我正在尝试做的一个例子:

注意:以下所有元素都在同一个数组中

    McDonalds, 10
    Marshalls, 10
    Dillards,  10
    Burger King, 5
    Hunan Palace, 5
    Taco Bell, 5
    Pizza Hut, 5
    Macy's, 2
    Prudential, 2
    Nike, 2
    Billabong, 2

我想最终得到类似的东西:

        Marshalls, 10
        Dillards,  10
        McDonalds, 10
        Hunan Palace, 5
        Burger King, 5
        Pizza Hut, 5
        Taco Bell, 5
        Nike, 2
        Macy's, 2
        Billabong, 2
        Prudential, 2
4

3 回答 3

2

您需要洗牌,然后进行排序

编辑

$array = array(
   array('company' => 'McDonalds', 'priority' => 10),
   array('company' => 'Marshalls', 'priority' => 10),
   //...
);

shuffle($array); //shuffles (randomizes the order of the elements in) an array

function custom_sort($left, $right) {
    return $right['priority'] - $left['priority'];
}

usort($array, "custom_sort"); // sort by user-defined comparison function

洗牌人
排序人

于 2012-10-31T07:31:46.667 回答
1

使用 排序时usort,当您具有相同的优先级时,按添加到数组中每个元素的随机因子进行排序:

$myArray = array(
   array('company' => 'McDonalds', 'priority' => 10),
   array('company' => 'Marshalls', 'priority' => 10),
);

foreach($myArray as &$elem){
    //add new property
    $elem['random_factor'] = rand(0,65535);
}

现在按优先级排序,然后按随机因素排序:

function sort_and_shuffle($a,$b){
    if($a['priority'] == $b['priority']){
        if($a['random_factor'] == $b['random_factor']){
            return 0;
        }
        return return ($a['random_factor'] < $b['random_factor']) ? -1 : 1;
    }else{
        return return ($a['priority'] > $b['priority']) ? -1 : 1;
    }
}

不要尝试在每个相同的优先级上返回随机结果,如下所示:

function sort_and_shuffle($a,$b){
    if($a['priority'] == $b['priority']){
        return rand(-1,1);
    }else{
        return return ($a['priority'] > $b['priority']) ? -1 : 1;
    }
}

它效率低下,在最坏的情况下它可以永远运行,因为在比较相同元素时没有恒定的结果

于 2012-10-29T20:17:38.647 回答
0

这是另一种方式,可以避免您弄乱您的数据。从您的基本usort()通话开始。

$places = array(
    array('name'=>'Marshalls', 'priority'=>10),
    array('name'=>'Pizza Hut', 'priority'=>5),
    ...
);

usort($places, function($left, $right) {
    return $right['priority'] - $left['priority'];
});

现在您需要一个函数,该函数将接收一个小数组,将其打乱,然后将其附加到一个更大的数组中。

function shuffleAndAppend(&$temp, &$final) {
    shuffle($temp);
    array_splice($final, count($final), 0, $temp);
    $temp = array();
}

现在,您可以遍历已排序的数组并将具有相同优先级的项目组合在一起,将它们打乱,然后将它们附加到最终数组中。

$shuffledPlaces = array();
$tempPlaces = array();
$lastPriority = -1;

foreach ($places as $onePlace) {
    if ($onePlace['priority'] != $lastPriority)
        shuffleAndAppend($tempPlaces, $shuffledPlaces);
    array_push($tempPlaces, $onePlace);
    $lastPriority = $onePlace['priority'];
}
shuffleAndAppend($tempPlaces, $shuffledPlaces);

print_r($shuffledPlaces);
于 2012-10-29T20:45:24.053 回答