[英]Shuffle only same value associative array in PHP
My array is我的数组是
$rank = [
'20' => 1,
'30' => 1,
'40' => 2,
'50' => 2,
'60' =>3,
];
expected op预期操作
$rank = ['30' => 1,'20' => 1,'50' => 2,'40' => 2,'60' =>3]; $rank = ['30' => 1,'20' => 1,'50' => 2,'40' => 2,'60' =>3];
I want ranking random means only rank 1(value) should shuffle, later rank 2 should shuffle.我想要随机排名意味着只有排名 1(值)应该洗牌,后来的排名 2 应该洗牌。 later 3 and so on.. how to do it this in PHP?后来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));
First step can be to collect all values(say roll numbers) in an array( say a set) grouped by ranks nicely.第一步可以是在一个数组(比如一个集合)中收集所有值(比如卷号),并按等级很好地分组。
Now, get all the unique ranks from your array.现在,从您的阵列中获取所有独特的排名。
Sort the ranks(skip this step and just run a for loop starting from 1 if ranks are sequential).对排名进行排序(跳过这一步,如果排名是连续的,则从 1 开始运行 for 循环)。
Loop over this unique ranks and get all roll numbers according to the rank in hand.循环遍历这个独特的排名,并根据手头的排名获得所有的卷号。
Shuffle() them and add all of them to your result. Shuffle() 它们并将它们全部添加到您的结果中。
Snippet:片段:
<?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;
}
Demo: http://sandbox.onlinephpfunctions.com/code/86c0ead227a06dda5c048dc9316c53788838bd65演示: http://sandbox.onlinephpfunctions.com/code/86c0ead227a06dda5c048dc9316c53788838bd65
you can use php function array_filter():您可以使用 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.