PHP - Loop Through Array, But Randomly?
If I have an array, $array, how can I loop through it (e.g. with a foreach() ) .. but just do it randomly?
So each time, random entries of the array are used and not necessarily in order. Similar TutorialsHi All,
I'm looking to update a mysql column weekly, where by 5 randomly selected rows are given a new random number, from between 1 and the num_rows / 5. This cycle is looped again until all the entries have a new random group for the week. It is to help mix up the players for teams for 5 aside. It needs to be able to accomodate the posibillity of the num_rows not dividing exactly by 5, using ceil perhaps?
As an example
Name Group
a 1
b 2
c 1
d 1
e 1
f 3
g 2
h 1
i 2
j 2
k 2
Then Next week
Name Group
a 2
b 1
c 2
d 2
e 1
f 2
g 3
h 1
i 2
j 1
k 1
I hope that makes sense. It'll be automated via cron job.
I've been really struggling with it, this is as far as I have got.
$totalgroupsraw = $num_rows /5; Hi there, I'd be ever so greatful if someone could help me please. I'm really trying to get my head around working with arrays and could really do with an example in a context i fully understand. I have made a test page for this and made a query that will search for appropriate records in my database: Code: [Select] <?php $colname_Class = "3"; $colname_Ships = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_Ships = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']); } mysql_select_db($database_swb, $swb); $query_Ships = sprintf("SELECT * FROM ships WHERE PlayerName = %s AND Class=%s AND Template='1'", GetSQLValueString($colname_Ships, "text"), GetSQLValueString($colname_Class, "int")); $Ships = mysql_query($query_Ships, $swb) or die(mysql_error()); $row_Ships = mysql_fetch_assoc($Ships); $totalRows_Ships = mysql_num_rows($Ships); echo $row_Ships['ShipID']; echo ' '; echo $row_Ships['ShipName']; echo ' '; echo $row_Ships['Class']; echo ' '; echo ' '; echo $totalRows_Ships = mysql_num_rows($Ships); ?> After i made the query i echo out the ShipID, ShipName and Class from the queey which displays: 5 New Ship 3 1 So you can see the ShipID = 5, the name of the Ship is New Ship, its Class is 3 and there is only 1 record found in the database that matches the search criteria. Lets say there are 10 records in my database... What i really need to do is make an array of the outputted results, determine the number of records and then to randomly choose 1 of the results from the array. Can you help me please?? If i can see an example in this context i feel i'd really learn something here. If you can help, please do because im well stuck. Thank you Tom I am working with wordpress. I am using a plugin that gets options stored in an array in the database. This is how I get the options Code: [Select] $options = get_option('option_tree'); echo $options['exc_cat']; the exc_cat is a key that stores a set of values. Right now with the code above, it echoes Array. If I do this Code: [Select] echo $options['exc_cat'][0]; it returns 5. Which is what I would expect it to do. What I can't figure out is how to get it to store each value which should be a number into 1 variable. What I need to do is loop through each value that is stored in the exc_cat key, return the number seperated by a -1,. So the result should look like this -1, -5 1 and 5 should be the only two numbers stored in the array at this point. Can you help? Thanks Code: [Select] // Get the users armour names $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); // Get the users overall protection $i=0; while($i < count($user_prot)) { $query1="SELECT * FROM armour WHERE id='$user_prot[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_prot[$i]=$array1["protection"]; $i++; } // set the users protection $user_protection=$armour_prot[0] + $armour_prot[1] + $armour_prot[2] + $armour_prot[3] + $armour_prot[4]; Is there a way to get them as one so: Code: [Select] $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $armour_prot[$i]=$array1["protection"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); Will that work and if so how would you then get the 2 different values out of say "$user_prot[0]". Cheers guys, Ruddy I have following in a csv file: sku,quantity,price ---------------------- ML2225-1/4,10,38.77 ML2225-1/4,20,36 ML2225-1/4,30,33.23 ML2225-5/16,10,35.94 ML2225-5/16,20,33.37 ML2225-5/16,30,30.8 ML2225-3/8,10,34.37 ML2225-3/8,20,31.92 ML2225-3/8,30,29.46 ML2225-7/16,10,34.37 ML2225-7/16,20,31.92 ML2225-7/16,30,29.46 ML2225-1/2,10,34.37 ML2225-1/2,20,31.92 ML2225-1/2,30,29.46 ... I am able to read the file (fgetcsv). How do I build an array for each unique sku set, then do something, then continue to the next unique sku set? Thanks, Mike How do i do if i've reached of array? i know i could do end of loop. but the array is present many times in my code. Code: [Select] while($row = mysql_fetch_assoc($getdetails)) { $people = $row['people']; $_SESSION['people'][] = $people; if(end($_SESSION['people'])) { //code } } i have an array in the loop but it isn't building up with results. i want it to check if the array exists, if not then create the array. Then in next loop it pushes a new value into the array. Below isn't working?... Code: [Select] while($row=mysql_fetch_assoc($get)); { $key = $row['keyword']; $scope= $_SESSION['scope']; if (!is_array($scope)) { $scopenew = array($key); $_SESSION['scope'] = $scopenew; } else { $scopenew = array_push($scope, $key); $_SESSION['scope'] = $scopenew; } } Hello, I'm trying to loop out the following value from the below array and cannot figure it out - orders.orderid Could anyone help me? stdClass Object ( [recsindb] => 4320 [recsonpage] => 10 [9] => stdClass Object ( [orders.orderid] => 83269442 ) [8] => stdClass Object ( [orders.orderid] => 83267681 ) )
echo "<pre>"; i have 2 arrays... first array of lastnames, second array of firstnames lastAry = array('smith', 'jones', 'reed', 'chan') firstAry = array('mary', 'chris', 'kim', joe', 'sara', 'tim', 'amy', 'fred') how do i loop through each lastnames and turn into a string with firstname so it looks like : smith | mary | chris jones | kim | joe reed | sara | tim chan | amy | fred Hello everyone! I am new here and this is my first post. I have been a member at another forum which they tend to make fun of newbies instead of helping them learn. That is why I am here Below is my script that allows me to upload 6 images at once and this works nicely. However, I am trying to change the variable $newname to increment in each pass so that I can build some if statements for my sql query. I would like the variable to start from $newname1 and should end up with 6 of them with the last being $newname6. That way I can have 6 unique picture variables that I can either update or insert into my table. Any help here would be great! Code: [Select] $upload_image_limit = 6; // How many images you want to upload at once? define('MAX_SIZE', '100'); define('UPLOAD_DIRECTORY', '../memberYard'); // Define a list of extensions we want to allow. $allowable = array('.gif', '.jpg', '.jpeg', '.png'); $errors = array(); if (isset($_POST['Submit'])) { if (!empty($_FILES)) { foreach ($_FILES as $file) { // No need for a separate function to get a file's extension $extension = substr($file['name'], strpos($file['name'], ".")); $size = filesize($file['tmp_name']); // Check if the file's extension is in the permissable list if (!in_array(strtolower($extension), $allowable)) { $errors[] = "File {$file['name']} is of an unknown type."; continue; } // Check that the file size is OK if ($size > MAX_SIZE * 1024) { $errors[] = "File {$file['name']} is too big."; continue; } // Generate a random name for the file and move it $newname = substr(md5(microtime()), 0, 12) . $extension; $copied = move_uploaded_file($file['tmp_name'], UPLOAD_DIRECTORY . DIRECTORY_SEPARATOR . $newname); if ($copied === FALSE) { $errors[] = "File {$file['name']} could not be uploaded."; } } } } ?> <div id="mainWrapper"> <div id="main"> <div class="top_bg"></div> <div class="description_pane"> <h2>Upload More Photos</h2> <?php if (!empty($errors)) { echo "<ul>"; foreach ($errors as $error) { echo "<li>{$error}</li>"; } echo "</ul>"; } ############################### HTML FORM while($i++ < $upload_image_limit){ $form_img .= '<label>Image '.$i.': </label> <input type="file" name="image'.$i.'"><br /><br />'; } $htmo .= ' <form method="post" action="" enctype="multipart/form-data"> '.$form_img.' <br /> <input type="submit" value="Upload Images" name="Submit" style="margin-left: 50px;" /> </form> '; echo $htmo; ?> <br /> </div> </div><!--end main --> <div class="main_bottom"></div> </div><!--end mainWrapper --> <? include '../templates/footer.php'; ?> Hi I am trying to tidy up a bit of php code to make the end display much better but I am a bit stuck, I have the following code which takes a mysql query and uses the result to create a google graph. <?php $str = ""; $str .= "<img src='http://chart.apis.google.com/chart?chs=600x300"; $str .= "&chd=t:"; $i=0; while($row_Recordset3 = mysql_fetch_assoc($Recordset3)){ $reading_array[$i] = $row_Recordset3['reading']; $date_array[$i] = date("j/n", strtotime($row_Recordset3['date'])); $i ++; } $count=0; $count = count($reading_array); if($count>1) { $rstring = implode(",", (array_reverse($reading_array))); $dstring = implode("|", (array_reverse($date_array))); }else{ echo $count; } $str = $str.$rstring; $str = $str."&cht=lc&chxl=0:|"; // We will close the src attribute with \' and to print escape character ' we shall precede it with \ $str = $str.$dstring; $str = $str."&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity Generation for the last 35 days'"; $str = $str." >"; //we shall echo the $str that will display the graph ?> <tr><td> <?php echo $str; ?> Currently the result is http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|28/10|29/10|30/10|31/10|1/11|2/11|3/11|4/11|5/11|6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days I need to make it display only every 7 dates so that they are readable but I still need the pipes in between to space out the dates correctly so they tie in with the correct point on the graph, like this where I manually removed some dates as a demo http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|||||1/11|||||6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days This is beyond my limited stills, can anyone help please? Thanks Gordon How can I loop an array and process in groups 100 at a time? Hi guys, Need some help with arrays! The following code puts ALL dates into an array, or should I say should. Because this: do { $start = $row_getCalendarDates['page_date']; $end = $row_getCalendarDates['page_date02']; $init_date = strtotime($start); $dst_date = strtotime($end); $offset = $dst_date-$init_date; $dates = floor($offset/60/60/24) + 1; $booked=0; while ($booked < $dates) { $newDateFinal[] = date("Y-m-d", mktime(12,0,0,date("m", strtotime($start)), (date("d", strtotime($start)) + $booked), date("Y", strtotime($start)))); $booked++; } print_r($newDateFinal); } while ($row_getCalendarDates = mysql_fetch_assoc($getCalendarDates)); Infact prints something like so when i have multiple results: Array ( [0] => 2010-12-01 [1] => 2010-12-02 [2] => 2010-12-03 ) Array ( [0] => 2010-12-01 [1] => 2010-12-02 [2] => 2010-12-03 [3] => 2010-11-01 [4] => 2010-11-02 [5] => 2010-11-03 [6] => 2010-11-04 [7] => 2010-11-05 [8] => 2010-11-06 [9] => 2010-11-07 [10] => 2010-11-08 ) These are 2 results coming from the database, so what it is doing is putting both into arrays, but I 'NEED' them iin a single array, how on earth do I go about doing this? Note however, how the first array has the first set of results but the second has them all ... this is affecting my code and so, need to somehow reference and get rid of the first array. Hope someone can help! Regards, Joe. These are my tables and fields. student_info(table) contains ( id(PK), student_name) student_subject(table) contains ( id(PK), student_id(FK), subject_name) below is my query: Code: [Select] $getRecords= mysql_query("select student_info.id, student_name, student_subject FROM student_info,student_subject WHERE student_info.id = student_subject.student_id"); while($getresult=mysql_fetch_assoc($getRecords)) { $arr[] = array('id' => $getresult['id'], 'subjects' => $getresult['subject_name'], 'name' => $getresult['student_name']), } In student_subject table I have at least 5 subjects(different rows) pointing to the same student. But the variable subjects in the array can only get 1 value how I can get those other subjects . I need simple solution/query coz I just started learning about this. Thank you for your help HI all, I need help to get data out of an array using a while loop or something simalar. What I have, is this: <?php $data = array( 1 => array( "name" => "Jordan Smith", "age" => "16 Years 0 Months" ), 2 => array( "name" => "Olivia Smith", "age" => "13 Years 12 Months" ) ); Now, what I did, is I constructed this: while($result=$data[1]) { echo $result['name']; } But it echoed "Jordan Smith" for infinity down the page. If anyone can help be do this, it will be great. Thanks I am trying to initialize every value in my $errors array to have a value of '' so I don't get "undefined variable" errors! Here is what I have... Code: [Select] //Put in some values and then try to erase them. $errors = array('firstName' => 'Enter First Name', 'lastName' => 'Enter Last Name'); //Want an initialized array. foreach($errors as $key => $value){ $key = ''; } But that doesn't seem to work when I run Code: [Select] print_r($errors, true); Thanks, Debbie Hello all! I can't seem to wrap my head around how to accomplish my problem. Here's my problem. I have several array's (only two this example). Code: [Select] <?php $item_num = array ( 0 => "00000", 1 => "00001", 2 => "00002" ), $item_disc = array ( 0 => "Some info for 0", 1 => "Some info for 1", 2 => "Some info for 2" ) ?> I want to build a table using the arrayed information. Something like: Code: [Select] <table> <tr> <td><input value="'.$item_num[0].'" name="item[]" size="9"></input></td> <td><input value="$item_disc[0]" name="disc[]" size="33"></input></td> </tr> <tr> <td><input value="'.$item_num[1].'" name="item[]" size="9"></input></td> <td><input value="$item_disc[1]" name="disc[]" size="33"></input></td> </tr> <table> I know how to loop through an array but this is a bit different in that I each array would need extracted in the loop. If you notice I want to build rows and the values for each row are in separate arrays. So $item_num and $item_disc are in the same row and exacts ['0'] and the next row is [1] and the next row is [2], etc... Any help would be great. Thanks. viviosoft - Hello gurus, I've been pounding my head against the wall on this one. It must be something simple I'm missing. I have a text field that posts ($_POST['case_ids']) a comma separated value such as 10067,10076 When I use explode to break it up it should make it an array. However when I use it in a foreach loop I get an invalid argument error. If I do a check for is_array() it fails the check. If I print the array I get: Code: [Select] Array ( [0] => 10067 [1] => 10076 ) So I thought maybe I get the error because the individual array elements don't have commas between them so I wrote this to put commas in between each element except the last: Code: [Select] $cases = array(); $numItems = count($case_ids);//get count of array $i = 0;//initialize counter foreach($case_ids as $key => $value){ if($i+1 != $numItems) { $cases[$key] = $value.','; }else{ $cases[$key] = $value; }//end if $i+1 $i++; } However this new array still gets the invalid argument error. Are these not valid arrays? Any help would be greatly appreciated. Thanks in advance, Twitch How do I post a for loop array in the next page. I am printing Question ID and choices for these and would like the for loop to print Question ID and choice that are checked for these. If the choice is ticked then it shoul return a 1 if the choice is empty then it should print 0. and I would like to insert this to a new table. How would I do this. Code: [Select] $intNum = 1; $intnumber = 1; while( $info = mysql_fetch_array( $sqll )){ echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> "; echo " $intNum, {$info['Que_Question']} <br />\n"; $intNum++; ?> <br> <?PHP for ($i =1; $i < 5; $i++) { echo "<input type=\"checkbox\" name=\"choice[{$intnumber}]\" />{$info['Que_Choice'.$i]}"; $intnumber++; } this is my form that print the question and it works fine. Code: [Select] <?PHP foreach ($_POST["Que_ID"] as $question) { $_POST["choice"] = $choice; echo "Question id: ".$question. $choice"<br />"; This is the post code but I know I need to do so much more but not sure how? Ayone help me or direct me to a source or tutorial or something. Ok so I'll try to explain what I'm trying to do the best I can. I want to build an array that allows me to add/remove/modify the variables used at any point in time without having to rebuild or rewrite a ton of new code. For example, below is an example list of variables I'd like to use in the array, followed by the code I would like to be automatically repeated. Example Variables: $materialName1, $materialName2, $materialName3, $materialName4, $materialName5, $materialName6 etc etc etc Example Code to repeat: Code: [Select] echo "<tr><td>Material: $materialName1</td><td>Rate: $materialName1Rate</td><td>Weight: $materialName1Weight</td></tr>"; Hopefully that makes sense. As always, very appreciated. |