Divide randomly generated ids into equal groups

569 views Asked by At

i'm using php and generating user's id like

 $id = bin2hex(openssl_random_pseudo_bytes(16, $s));

And i would like to divide these ids into equals (or almost equals) groups. And in future i would like to know which group user belongs to.

Any ideas? What criteria can i choose for this?

2

There are 2 answers

0
Dmitriy Apollonin On BEST ANSWER

I've found one variant of resolution. But maybe there is another, more pretty way...

$group = array_sum(str_split($id))%2;
0
Hektor On

OK this is a rough and ready answer; since the actual criteria you wish to sort on aren't given, I'm assuming the main goal is an even distribution of variables amongst your chosen container; I've used arrays here.

<?php


  $id1 = 'abc';
  $id2 = 'def';
  $id3 = 'ghi';
  $id4 = 'jk';
  $id5 = 'lmn';
  $id6 = 'opq';
  $id7 = 'rst';
  $id8 = 'uvx';

  $id_array = array($id1, $id2, $id3, $id4, $id5, $id6, $id7, $id8);

  $array1 = array();
  $array2 = array();
  $array3 = array();
  $array4 = array();
  $id_storage = array($array1, $array2, $array3, $array4);

  $id_storage_size = sizeOf($id_storage);


  foreach ($id_array as $indivId) {
          $id_array_size = sizeOf($id_array);

          $current_storage_array = $id_array_size % $id_storage_size; 
          $id_storage[$current_storage_array][] = $indivId;
          array_shift($id_array);
  }  


  //check them like so...
  echo $id_storage[1][1];


?>

As for checking which array contains a given value:

<?php

    $givenId = $id2;

    foreach ($id_storage as $indiv_storage_array){

            if (in_array($givenId, $indiv_storage_array)){
                  echo "Match found in $indiv_storage_array";
            } 
    }       
?>