[英]Shuffle only same value associative array in PHP
我的數組是
$rank = [
'20' => 1,
'30' => 1,
'40' => 2,
'50' => 2,
'60' =>3,
];
預期操作
$rank = ['30' => 1,'20' => 1,'50' => 2,'40' => 2,'60' =>3];
我想要隨機排名意味着只有排名 1(值)應該洗牌,后來的排名 2 應該洗牌。 后來3等等..如何在PHP中做到這一點?
function shuffle_array($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
echo "<pre>"; print_r(shuffle_array($rank));
第一步可以是在一個數組(比如一個集合)中收集所有值(比如卷號),並按等級很好地分組。
現在,從您的陣列中獲取所有獨特的排名。
對排名進行排序(跳過這一步,如果排名是連續的,則從 1 開始運行 for 循環)。
循環遍歷這個獨特的排名,並根據手頭的排名獲得所有的卷號。
Shuffle() 它們並將它們全部添加到您的結果中。
片段:
<?php
function getRandomizedSortedData($ranks){
$rank_set = [];
foreach($ranks as $roll_no => $rank){
if(!isset($rank_set[ $rank ])){
$rank_set[$rank] = [];
}
$rank_set[$rank][] = $roll_no;
}
$unique_ranks = array_unique($ranks);
sort($unique_ranks);
$result = [];
foreach($unique_ranks as $rank){
$roll_nos = $rank_set[$rank];
shuffle($roll_nos);
foreach($roll_nos as $roll_no){
$result[$roll_no] = $rank;
}
}
return $result;
}
演示: http://sandbox.onlinephpfunctions.com/code/86c0ead227a06dda5c048dc9316c53788838bd65
您可以使用 php function array_filter():
$rank = [
'20' => 1,
'30' => 2,
'40' => 3,
'50' => 2,
'60' => 1,
];
function filterRank1($value) {
return $value === 1;
}
function filterRank2($value) {
return $value === 2;
}
...
$rank1 = array_filter($rank, 'filterRank1');
$rank2 = array_filter($rank, 'filterRank2');
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.