简体   繁体   中英

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];

I want ranking random means only rank 1(value) should shuffle, later rank 2 should shuffle. later 3 and so on.. how to do it this in 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).

  • 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.

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

you can use 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');
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM