fixed number recurssion set in php - php

I have a fixed number recursion set with me. I need to get a random variable and get the left and right values and store them in an array. In the for loop i need to increment the array index...how do i go about it....if the uid is set to 1 it works perfect but in case of any other number i cannnot just get the logic....
the code is like this
// global id
$uid=3; // Take from session.
// Range Array
$range[0]=$uid;
$range[1]=2; // level 0
$range[2]=4; // level 1
$range[3]=8; // level 2
$range[4]=16; // level 3
$range[5]=32; // level 4
$range[6]=64; // level 5
$range[7]=128; // level 6
$range[8]=256; // level 7
$range[9]=512; // level 8
$range[10]=1024; // level 9
$range[11]=2048; // level 10
// Range array ends.
$gar[0]=$uid;
$leftid=$uid*2;
$rightid=($uid*2)+1;
// Generate Levels
//Level 1. 2 Elements
$gar[1]=$leftid;
$gar[2]=$rightid;
// Level 2. 4 elements
// range starts with element 1 of range array.
$i=($gar[1]*2);
$ip=($i+$range[2])-1;
$ak=3;
for($x=$i; $x<=$ip; $x++)
{
$gar[$x-1]=$x;
}
var_dump($gar);
The output is as follows if uid is set to 3. If you see the array key has not incremented..
array (size=7)
0 => int 3
1 => int 6
2 => int 7
11 => int 12
12 => int 13
13 => int 14
14 => int 15

Related

How to allow duplicate mysql row id in array?

My data in table t1 as below (only 2 record),
+-----------+-----------------+----------+
| shid | lvlmin | lvlmax |
+-----------+-----------------+----------+
| 1 | 1 | 10 |
| 2 | 5 | 10 |
+----------------------------------------+
My php code is:
$userinfo[0] = '9';
$ghunt = DB::fetch_all("SELECT shid FROM t1
WHERE lvlmin <= ".$userinfo[0]." AND lvlmax >= ".$userinfo[0].
"ORDER BY rand() LIMIT 5");
print_r($ghunt);
Result got 2 array:
Array ( [0] => Array ( [shid] => 2 ) [1] => Array ( [shid] => 1 ) )
How do I do when the array result is less than the LIMIT 5 in mysql query, auto use the array result in $ghunt to fill up the array?
What I mean is:
Array (
[0] => Array ( [shid] => 2 )
[1] => Array ( [shid] => 1 )
[2] => Array ( [shid] => 2 )
[3] => Array ( [shid] => 1 )
[4] => Array ( [shid] => 1 )
)
The shid can be random place in array.
Why don't you do something like this?
If (count($ghunt) < 5){
$realResultCount = count($ghunt);
for ($i = realResultCount; $i <= 5; $i++){
$ghunt[$i] = $ghunt[rand(0,realResultCount-1)];
}
}
Basically, what above code does is, if ghunt has less than 5 records in it, it tops it up to 5, by randomly selecting records out of initially returned records.
I don't code PHP, but I can describe one way you can achieve your goal simply. Most languages have a MOD operator, usually % - the php manual page for mod is here
It gives us the remainder of a division operation, so 10 mod 3 is 1, because 10 divided by 3 is 9 remainder 1
A useful property of MOD then, is that it always cycles between 0 and 1 less than what you're modding by. If you mod an incrementing number by 5, the result will always be 0,1,2,3,4,0,1,2,3,4 in a cycle. This means you can have a for loop with some incrementing number, mod by an array length and the result will be an integer that is certainly an array index. If the loop variable goes higher than the end of the array, the mod operator will make it wrap round to the start of the array again
MyArray[ 1746262848 mod MyArray.length ]
Will certainly not crash, even if the array only has 2 items
So for your case, just have a loop.. make he following pseudo code into PHP
// run the loop 5 times
For I as integer = 0 to 4 do
Print MyArray[ i mod MyArray.length ]
If you have 2 items in your array, A and B, it will simply print ABABA
If you have 3 items A B C it will print ABCAB
Hopefully this info will be helpful to you for implementing a solution in php for this, and many future problems. Mod can be really useful for implementing various things when working with arrays

array_rand returning same value

I am having a problem returning random array keys if the specified number of entries is the same as the number of items in the array.
$rdm = array_rand($similar_product_array, 4);
will always return key values 0, 1, 2, 3 if there is 4 items in the array.
for example:
// Items in array
array (size=4)
0 => string 'Batman Heroes Edition Nendoroid' (length=31)
1 => string 'Oberyn' (length=6)
2 => string 'White Walker' (length=12)
3 => string 'Avengers Age of Ultron Hulk' (length=27)
// "randomly" generated array keys is always 0 , 1, 2, 3
array (size=4)
0 => int 0
1 => int 1
2 => int 2
3 => int 3
however, if i have:
$rdm = array_rand($similar_product_array, 3);
// Returns randomly as expected
array (size=3)
0 => int 0
1 => int 2
2 => int 3
it will return randomly generated keys as it should.
What could i be doing wrong here?
You misunderstood purpose of array_rand() function, it is supposed to give you random entries from array, but not in random order. That means that if you are asking for 4 random items from array with 4 items, it will always return all the items (in the original order).
If you just need to change randomly the order of array entries, use shuffle() function, for example in this way:
$array_copy = $array;
shuffle($array_copy);
$rdm = array_rand($array_copy, <how_many_you_need>);

Getting all ancestors of an element from a table

I am building a badges app in CodeIgniter using a MySQL database. There are 3 types of badges: level 1, level 2 and level 3 badges.
Each level 2 badge is awarded once you get all the required level 1 badges and each level 3 badge is awarded once you get all the required level 1 and level 2 badges. There is also a level 3 badge that requires getting 4 level 3 badges.
I have the following database table for my badges relations:
badge_id - children_id
1 - 20
1 - 25
20 - 40
20 - 45
26 - 40
25 - 39
40 - 50
I need a function that returns me all the ancestors of a badge.
For example, if the function recieved the argument 50 it would return: 40, 26, 20, 1. Any ideas?
If you want to handle it by pure mysql, you need to declare a mysql stored procedure which has some depth limitations.
Instead of that I would recommend using a simple recursive PHP function to return what you need:
function get_ancestors($child_id, $badges)
{
$found = array();
foreach($badges as $k => $row){
if ($row['children_id'] == $child_id){
$found = array_merge($found, get_ancestors($row['badge_id'], $badges));
$found[] = $row['badge_id'];
}
}
return $found;
}
The $badges variable holds all the rows from your badges relations table, just simply read it out from the database.
Based on the example you gave, for the following call
get_ancestors(50, $badges);
the output would be:
Array
(
[0] => 1
[1] => 20
[2] => 26
[3] => 40
)

Removing items from an array php

I'm new to php so please take it easy.
I have created an array of integers. 1-100. What I want to do is shuffle the array and remove random numbers from it leaving only lets say 15 numbers.
This is what I have done so far, can't figure out how to remove the random numbers. I know I could possibly use unset function but I'm unsure how could I use it in my situation.
// Create an Array using range() function
$element = range(1, 100);
// Shuffling $element array randomly
shuffle($element);
// Set amount of number to get rid of from array
$numbersOut = 85;
// Remove unnecessary items from the array
var_dump($element);
Just try with:
$element = range(1, 100);
shuffle($element);
$output = array_slice($element, 0, 15);
var_dump($output);
Output:
array (size=15)
0 => int 78
1 => int 40
2 => int 10
3 => int 94
4 => int 82
5 => int 16
6 => int 15
7 => int 57
8 => int 79
9 => int 83
10 => int 32
11 => int 13
12 => int 96
13 => int 48
14 => int 62
Or if you want to use $numbersOut variable:
$numbersOut = 85;
$output = array_slice($element, $numbersOut);
It will slice an array from 85 to the end. Remember - if you will have 90 elements in the array, this method will return just 5 elements.

PHP array key to value mappings question

I just saw this on php.net description of how key to value mapping works:
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
I just cant quite understand how 11 could be assigned key 6. I know 5 is not possible since it is already used on the second element as a key so it makes sense to jump it over.
But should not be 11 intuitively assigned key 4 in the first place since the first element of the array 10 is assigned key 0 and therefore the key value is incremented 0..1..2..3..4 from that point according to the first index unless specified otherwise (e.g 5=>6 could have had key 1, 3=>7 with key 2, and 'a'=> 4 could have had key 3 if not specified)? And also, why does it say that 11 should be assigned a key that represents the maximum integer of indices (in this case 6 since 5 was used already)?
Would appreciate any help/clarification. Please let me know if the question needs to be clarified. Thanks much.
It is implemented in this way just because it is the most performant solution - to just use maximum_specified_key + 1, rather than to find a hole in enumration
I believe it has to do with the way that PHP arrays work. Each has an internal cursor for the each, current, next, pos and similar methods. My guess: as a new key is specified, if it is higher than the current cursor, the cursor is advanced to that position so that anything added after that point will still be at current position + 1.
And also, why does it say that 11
should be assigned a key that
represents the maximum integer of
indices (in this case 6 since 5 was
used already)?
Why not? As zerkms says, it's performant, so there's that.
It's also more or less what you might expect. Given an array with mixed keys like that, what would you expect array_push() to do?
Of course, if you're running into this kind of thing in real life, it's probably time to stop and consider some amount of refactoring. Arrays in PHP are very flexible, and these somewhat arbitrary decisions had to be made. They're documented. The only alternative is to make array usage much more rigid.
The PHP manual gives you the answer in the link you provided:
As mentioned above, if no key is specified, the maximum of the
existing integer indices is taken, and the new key will be that
maximum value plus 1 (but at least 0). If no integer indices exist
yet, the key will be 0 (zero).
The code:
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
So far the maximum key when you get to 'a' is 5 so the next available key according to the php manual would be 5 + 1 i.e. 6.
Note that the maximum integer key used
for this need not currently exist in the array. It need only have
existed in the array at some time since the last time the array was
re-indexed.
// empty the array;
foreach( $switching as $key => $value ) {
unset( $switching[$key] );
}
// refill it with new elements
for( $i = 0; $i < 10; $i++ ) {
$switching[] = $i + 1;
}
output array:
Array
(
[9] => 1
[10] => 2
[11] => 3
[12] => 4
[13] => 5
[14] => 6
[15] => 7
[16] => 8
[17] => 9
[18] => 10
)

Categories