Divide randomly generated ids into equal groups - php

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?

I've found one variant of resolution. But maybe there is another, more pretty way...
$group = array_sum(str_split($id))%2;

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";
}
}
?>

Related

Generate all combinations of elements between arrays

I have multiple arrays that contain multiple elememts, for example:
$array1 = (1,2)
$array2 = (3,4)
I need to generate all possible combinations for elements of arrays. For given example, the output should be:
1_3, 1_4, 2_3, 2_4
However, the issue is that both number of arrays and amount of elements in each one can be different. So we can also take something like that:
$array1 = (1,2,3,4)
$array2 = (5,6,7)
$array3 = (8,9,10,11,12)
and output should look like that:
1_5_8, 1_5_9, 1_5_10 etc. until 4_7_12.
How do I implement something like that? I know that I should use foreach loop, but I have no idea what to do if amount of "foreaches" can be different every time I execute algorithm.
Any help is really appreciated :)
<?php
$array1 = [1,2,3,4];
$array2 = [5,6,7];
$array3 = [8,9,10,11,12];
$collection = [$array1,$array2,$array3];
$result = $collection[0];
array_shift($collection);
foreach($collection as $each_array){
$temp = [];
foreach($result as $each_sub_result){
foreach($each_array as $each_item){
$temp[] = $each_sub_result."_".$each_item;
}
}
$result = $temp;
}
print_r($result);
Algorithm:
We collect all arrays in our $collection variable.
Now, we loop over all elements of our $collection variable where each individual item is an array.
I have done an array_shift() since we are assigning first element of $collection to $result(so we don't want to iterate over them again).
We maintain $temp to store temporary results. Note that we use $result also to store temporary results, so that we can iterate over it and get new temporary results. By temporary, I mean building the final array. For example: It starts with 1, then 1_5 and then finally 1_5_8.
After the looping completes, we will have our final answer in $result.
try something like this:
$array1 = array(1,2,3);
$array2 = array(4,5,6);
foreach ($array1 as $a1){
foreach ($array2 as $a2){
echo $a1 . '_' . $a2 . ', ';
}
}
You can expand it like you wish.
I'm good in JS so that's why I did the algo in JS, you can try to do this in PHP,,no much difficult. You just have to pass in all the array is the function and the rest should be done by itself. Let me know if any confusions.
var arr1 = [1, 2, 3];
var arr2 = [4, 5];
var arr3 = [6, 7, 8];
var numberOfArrays = -1;
function processArrays(concatWith = [], allArrays) {
const duplicateArray = [...allArrays];
for (var i = 0; i < allArrays.length; i++) {
const currentArray = duplicateArray.splice(0, 1);
currentArray[0].forEach(function (value) {
concatWith.push(value);
processArrays(concatWith, duplicateArray);
if (concatWith.length === numberOfArrays) {
console.log(concatWith.join('_'));
}
concatWith.pop();
});
}
}
function makeCombinations(arrayOfAllArrays = []) {
numberOfArrays = arrayOfAllArrays.length;
processArrays([], arrayOfAllArrays);
}
makeCombinations([arr1, arr2, arr3]);

php add array element to array of arrays

I use PHP 5.5, but my working knowledge is very limited - I am only just learning. I cant' get my code to work.
I have an array EP with 20 values. I shuffle these values for every new visitor of the site, so they are always in a random order.
$EP = array(30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220);
$EP = shuffle($EP);
I have an array of other arrays
$P[] = [81,102,74,157,93,106,0,0]
$P[] = [71,102,76,157,93,106,0,0]
$P[] = [91,102,74,7,93,106,0,0]
$P[] = [56,100,89,15,93,106,0,0]
20 in total
What I need is that every element of the EP array is used one time, and then a 0 added at the end, so it looks like this:
$P[] = [81,102,74,157,93,106,0,0,$EP(0),0];]
$P[] = [71,102,76,157,93,106,0,0,$EP(1),0];]
$P[] = [91,102,74,7,93,106,0,0,$EP(2),0];]
$P[] = [56,100,89,15,93,106,0,0,$EP(3),0];]
so that all 20 array elements of EP are used.
My code which worked, until I add the EP array and added EP(1) etc in my other arrays.:
<?php
$Return = array();
$P = array();
$S = array();
$F = array();
$EP = array(30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220);
$EP = shuffle($EP);
//ts1
$P[] = [81,102,74,157,93,106,$EP(0),0];
$S[] = [this series is not important fo rmy question];
//ts2
$P[] = [184,0,0,0,0,0,0,105,$EP(1),0];
$S[] = [..];
//ts3
$P[] = [0,0,0,0,0,$EP(2),0];
$S[] = [..];
//and so on till time series ts20
//for loop below worked until I added the EP series, so it must have something to do with how I call the EP elements from the array.
for($i=0; $i<count($P); $i++)
{
$Return[] = $P[$i];
$Return[] = $S[$i];
$Return[] = $F[$i];
}
die(json_encode($Return));
?>
I see two things going wrong:
shuffle() doesn't return an array. It returns a bool. When you do $a = shuffle($a);, $a will be true or false - not a shuffled array. Do instead: shuffle($a);.
When you want to refer to an index in an array, don't use $a(10). Use $a[10]. See php.net.
After changing that, it should work (tested).
You can push to the array
array_push($P, $EP);
This will add a new array element to $P;

How to implode many available to one available using loop for?

How to implode many available to one available using loop for ?
i have many available like
$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;
and then i want to implode to one available
$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,
but i want to using loop for like this
for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}
how can i do ? thank you for every comment ^^
$all_data = implode(',', array($var_1, $var_2, ..., $var_11));
Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.
For the for loop you're trying to write, see the PHP documentation on Variable Variables.
$all_data = '';
for ($i = 1; $i < 12; $i++) {
$all_data .= ${'var_'.$i} . ',';
}

Creating a ranked list from multiple arrays

I have 3 arrays that return a url,title,snippet and score from 3 different search engines, the score starts at 100 for the element in the array, the second 99 and so on, I'm trying to combine all 3 into one array. If the urls match from the different arrays I want to add the scores together and then delete the duplicate url. If there is no match between the urls then I just want to put this element into the combined array.
The final combined list should contain all distinct urls with its score,title and snippet, here are my array structures
googleArray
$x=0;
$score=100;
foreach ($js->items as $item)
{
$googleArray[$x]['link'] = ($item->{'link'});
$googleArray[$x]['title'] = ($item->{'title'});
$googleArray[$x]['snippet'] = ($item->{'snippet'});
$googleArray[$x]['score'] = $score--;
$x++;
}
blekkoArray
$score = 100;
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = ($item->{'url'});
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score--; // assign the $score value here
$i++;
}
bingArray
foreach($jsonObj->d->results as $value)
{ $i = 0;
$bingArray[]['Url'] = ($value->{'Url'});
$bingArray[]['Title'] = ($value->{'Title'});
$bingArray[]['Description'] = ($value->{'Description'});
$bingArray[]['score'] = $score--;
$i++;
}
Any help would be great, thanks in advance
This solution depends on a couple of things to work. First, the url and score keys need to be the same, i.e. all lower case and none that are "link." Secondly, the URLs have to be normalized, because they serve as the key for the array. If there are any differences in the URLs, they will show up more than once in the final array.
$merged = array_merge($googleArray, $blekkoArray);
$merged = array_merge($merged, $bingArray);
$combined = array();
foreach ($merged as $key => $value){
$score = (isset($combined[$value['url']]['score'])) ? $value['score'] + $combined[$value['url']]['score'] : $value['score'];
$combined[$value['url']] = $value;
$combined[$value['url']]['score'] = $score;
}
If you don't want to keep the URLs as the key, add this line:
$combined = array_values($combined);
If you want to sort the array by score, you can use usort:
usort($combined, function ($a, $b){
return $b['score'] - $a['score'];
});
print_r($combined);

PHP - Add String to Array

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);

Categories