PHP - Restricting The Last Iteration In The Loop
So I have a very simple for loop that I am populating a list with levels and exp required to achieve the next level. I have been using a sandbox to test my output and have also created an excel sheet to replicate the data to verify the content. This code was not mine from the beginning and in creating the spreadsheet I discovered the flaw. Below is the code I am trying to fix: function experience($L, $pres = 0) { $a = 0; $end = 0; for ($x = 1; $x < $L; ++$x) { $a += $x * round($x + 5 * pow(4, ($x / 300))); } if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } if ($x > 399) { $a += $x * round($x + 11 * pow(4, ($x / 280))); } if ($x > 599) { $a += $x * round($x + 19 * pow(4, ($x / 270))); } if ($x > 799) { $a += $x * round($x + 35 * pow(4, ($x / 260))); } if ($x > 999) { $a += $x * round($x + 67 * pow(4, ($x / 250))); } return round($a / 1.25); } Below is the troubleshooting I am attempting to do (Modified and simplified for and while loop): //for loop $no = 200; $a = 0; for ($x = 1; $x < $no; ++$x) { $a += $x + 1; } if ($no > 199) { $a += $x + 2; } echo $a; //while loop $no = 200; $a = 0; $x = 1; while (($x - 1) < $no) { $a += $x * round($x + 5 * pow(4, ($x / 300))); $x++; if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } } echo $a; Upon request I can also provide snipets of the excel sheet. So the gist of what the issue I am having is this. Between level 199 and 200 the iteration of the loop is running one extra time through the initial formula. As you can tell at level 200, 400, 600, 800 and 1000 I want this formula to change so that it simplifies the amount of exp required to achieve the next level. I can not for the life of me figure out how to restrict the loop while still allowing the values 200 up to run through it for the first 199 iterations. The output I should get from the primary code for levels 199 through 201 are as follows: 199 = 200 = 201 = At level 199 I am good but for whatever reason it runs one additional iteration at the level 1-199 formula and then moves on to the 200 level formula messing up the values. Any and all help is much appreciated. I am a novice hobbyist at best and have been doing this for many, many years now but sometimes I get stumped. I chalk it up to lack of proper training and time to really be serious with it. Thanks in advance....NICON Similar TutorialsTo solve a bigger issue I'm having in WordPress, I have thrown together this basic script in PHP script to help me get to the bottom of it. Basically, I am trying to add a <hr /> tag after every 3rd paragraph: http://www.mattpealing-server.co.uk/~freshmat/wp-content/themes/match2move/test.php With the following code: <?php $count = 0; ?><?php while($count < 20) : ?><span><p><strong><?php echo $count; ?>:</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p></span><?php if ($count % 3) : ?><hr /><?php endif; ?><?php $count ++; ?><?php endwhile; ?>() However if you notice, this output just doesn't turn out like this! Does the operator I'm using not test if $count is a multiple of 3? I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#!
$start = 0; hi I'm coding a page and I was trying to iterate an iteration. but it doesn't seem to work. is this possible in php? Code: [Select] $pageTpl->setIteration('iPlaylist'); // loop all collections and output them foreach ($playlists as $playlist) { // assign collection & urls in template $pageTpl->assignIteration('playlist', $playlist['Title']); $pageTpl->refillIteration(); $pageTpl->setIteration('iMusic'); foreach ($songs as $song){ $pageTpl->assignIteration('path', STREAMING_PREFIX.substr($song['Filename'], 7)); $pageTpl->assignIteration('songId', $song['SongId']); $pageTpl->assignIteration('title', $song['Title']); $pageTpl->assignIteration('artist', $song['Artist']); $pageTpl->assignIteration('time', FYMFunctions::Sec2hms($song['Length'])); $pageTpl->assignIteration('genre', $song['Genre']); $pageTpl->assignIteration('delete', 'removeSong('.$song['SongId'].')'); $pageTpl->refillIteration('iMusic'); } // parseIteration $pageTpl->parseIteration('iMusic'); } // refillIteration $pageTpl->refillIteration(); // parseIteration $pageTpl->parseIteration('iPlaylist'); this is the piece of code... did I do anything wrong? Hello, I have two classes: Code: [Select] abstract class Serializable { public function serialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } class ToSerialize extends Serializable { public function otherSerialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } $foo = new ToSerialize(); $foo->serialize(); //This will return one thing $foo->otherSerialize(); //This will return something different Why does this happen? Hello,
Here is my code:
<?php require 'vendor/autoload.php'; $client = new Elasticsearch/Client(); $root = realpath('~/elkdata/for_elk_test_2014_11_24/Agencies'); $iter = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD); $paths = array($root); foreach ($iter as $path => $dir) { if ($dir -> isDir()) { $paths[] = $path; } } //Create the index and mappings $mapping['index'] = 'rvuehistoricaldocuments2009-2013'; //mapping code $mapping['body'] = array ( 'mappings' => array ( 'documents' => array ( '_source' => array ( 'enabled' => true ), 'properties' => array( 'doc_name' => array( 'type' => 'string', 'analyzer' => 'standard' ), 'description' => array( 'type' => 'string' ) ) ) ) ); $client ->indices()->create($mapping) //Now index the documents for ($i = 0; $i <= count($paths); $i++) { $params ['body'][] = array( 'index' => array( 'type' => 'documents' 'body' => array( 'foo' => 'bar' //Document body goes here ) ) ); //Every 1000 documents stop and send the bulk request. if($1 % 1000) { $responses = $client->bulk($params); // erase the old bulk request $params = array(); // unset the bulk response when you are done to save memory unset($responses); } } ?>I am looking to index a large amount of documents using elastic search and php. I have a very complex directory filled with other directories that i need to index into an array. I wanted to see if my code looked right, and if not what am I doing wrong? Thanks, Austin Harmon I have a search code for my site and I want to narrow the scope of the search with a drop down that will allow users to pick a state, ( the sql table includes a state field ) or set the script so that i will only search for results for a particular state. In the sql select I have tried every way of using WHERE venue_state='NY' but it will not work. I would really rather allow the users to select a state from a dropdown and then enter the search term - city, zip or venue name. Thank you for looking Code: [Select] <?php include('config.db.php'); $find = trim($_GET['find']); $field = $_GET['field']; if($find && $field) { // we have search form submitted // check for values to prevent sql injection $valid_fields = array("venue_zip", "venue_city" , "show_name"); if(!in_array($field, $valid_fields)) die("Error: Invalid field!"); $rpp = 10; // results per page $adjacents = 4; $page = intval($_GET["page"]); if(!$page) $page = 1; $reload = $_SERVER['PHP_SELF'] . "?find=" . urlencode($find) . "&field=" . urlencode($field); echo "<h4>Search Results for $find</h4>\n"; $find = addslashes($find); $result = mysql_query("SELECT *, DATE_FORMAT(`start_date`, '%b %e, %Y') AS s_date FROM craft_shows WHERE $field LIKE '%$find%'"); if(mysql_num_rows($result) == 0) { echo "<p>0 matches found.</p>"; } else { echo "<table class='table7' cellpadding='2'>"; echo "<tr><td> </td><td><strong>Date</strong></td><td><strong>Show Name</strong></td><td><strong>City</strong></td><td><strong>Attendance</strong></td></tr>"; echo "<tr><td colspan='5'><hr class=\"hr2\"></td></tr>"; // count total number of appropriate listings: $tcount = mysql_num_rows($result); // count number of pages: $tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number $count = 0; $i = ($page-1)*$rpp; while(($count<$rpp) && ($i<$tcount)) { mysql_data_seek($result,$i); $row = mysql_fetch_array($result); $id = $row['id']; echo "<tr><td>"; echo "<a href=\"/show_submits/show_detail.php?id=$id\">Details</a>"; echo "</td><td>"; echo $row['s_date']; echo "</td><td>"; echo $row['show_name']; echo "</td><td>"; echo $row['venue_city']; echo "</td><td>"; echo $row['venue_state']; echo "</td></tr>"; echo "<tr><td colspan='5'><hr class=\"hr3\"></td></tr>"; $i++; $count++; } echo "</table><br>"; function paginate_one($reload, $page, $tpages) { $firstlabel = "First"; $prevlabel = "Prev"; $nextlabel = "Next"; $lastlabel = "Last"; $out = "<div class=\"pagin\">\n"; // first if($page>1) { $out.= "<a href=\"" . $reload . "\">" . $firstlabel . "</a>\n"; } else { $out.= "<span>" . $firstlabel . "</span>\n"; } // previous if($page==1) { $out.= "<span>" . $prevlabel . "</span>\n"; } elseif($page==2) { $out.= "<a href=\"" . $reload . "\">" . $prevlabel . "</a>\n"; } else { $out.= "<a href=\"" . $reload . "&page=" . ($page-1) . "\">" . $prevlabel . "</a>\n"; } // current $out.= "<span class=\"current\">Page " . $page . " of " . $tpages . "</span>\n"; // next if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" .($page+1) . "\">" . $nextlabel . "</a>\n"; } else { $out.= "<span>" . $nextlabel . "</span>\n"; } // last if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" . $tpages . "\">" . $lastlabel . "</a>\n"; } else { $out.= "<span>" . $lastlabel . "</span>\n"; } $out.= "</div>"; return $out; } echo paginate_one($reload, $page, $tpages, $adjacents); } } ?> I am using the following to check that the user is logged on before he/she views pages on my site can I adapt what is here so that only some pages can be viewed by admin only? <?php include("../php/dbconnect.php"); //connects to the database //session code session_start(); //Check if user is authenticated if(!isset($_SESSION['username'])){ //User not logged in, redirect to login page header( "Location: http://webdev/schools/hhs/psy_bookings/" ); } else { //User is logged in, contiue (use session vars to diplay username/email) //echo "'Welcome, {$_SESSION['username']}. You are still logged in. <br />'"; // echo "'Your email address is: {$_SESSION['email']}.'"; }//end of session code ?> I assume this can be done somehow w/ PHP. How would I create a page which only displays based on detection of certain IP addresses and if the certain IP address is not detected, then redirects to a not allowed page. I have a list of the IP addresses to allow. Thanks in advance! just wandering if this can be done and if so do you know were i can read about this or have any suggestion? i have a database with all are clients data that we store in it. I can now let them log into a php search screen that they can pull data from and see what we have stored. I would like to restrict what info they can pull by the user name they log in with, so they are not pulling other client info when they do the search. the user database and company database are two different ones. they search by box number and i would like to restrict what it pulls up by company name depending on if the user logged in has rites to that company info. so if jane doe logged in and she was a member of soso company when she did a box search she would only see what was from soso company instead of how it is now it pulls from soso, DD, and all the company's. Thanks in advance I'm not entirely sure how to phrase the title, so I hope it's appropriate... I have an array which looks like the following.. Code: [Select] Array ( [contact] => Array ( [0] => Array ( [name] => Someone Cool [number] => 1234567890 ) ) [messages] => Array ( [0] => Array ( [message] => A message that was recieved [date] => 1234567890 [type] => 1 ) [1] => Array ( [message] => A message which was sent [date] => 1322175702616 [type] => 2 ) ) [calls] => Array ( [0] => Array ( [datetime] => 1320674980836 [type] => 1 [duration] => 7 [number] => 1234567890 ) [1] => Array ( [datetime] => 1320675327541 [type] => 2 [duration] => 638 [number] => 1234567890 ) ) ) [messages] can have anywhere between 40 and 3000 children [calls] can have anywhere from 0 to 200ish children ** These are generals, but realistically, either can have any number. What I'm trying to do is dump all messages and calls. The catch is this: When dumping a call, a check needs to be run against datestamps and only dump the next call coming out where the datestamp of the call is NEWER than the LAST message dumped, AND OLDER than the message that is to be dump in this cycle of the loop. What I have so far is the following... Code: [Select] foreach($vardump['messages'] as $message) { // So we have a reference point for the first call we're going to dump if(!is_numeric($last_message_stamp)) { $last_message_stamp = $message['date']; } if( trim($vardump['calls'][$calls_counter]['datetime']) > trim($last_message_stamp) && trim($vardump['calls'][$calls_counter]['datetime']) < trim($message['date'])) { // Dump the calls row! echo(" <div class=\"chatbubble-call\"> <div class=\"chatbubble-person\">".$vardump['contact'][0]['name']."</div> <p>".$vardump['calls'][$calls_counter]['number']."</p> <p>".date("h:i:s", $vardump['calls'][$calls_counter]['number'])."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $vardump['calls'][$calls_counter]['datetime'] / 1000)."</div> </div> "); // Increase our calls index $calls_counter++; } // Begin dumping Texts out :D // Let's see which style type we're dumping out... if($message['type'] == 2) { // Message Sent echo(" <div class=\"chatbubble-sent\"> <div class=\"chatbubble-person\">Pat Litke</div> <p>".$message['message']."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $message['date'] / 1000)."</div> </div> "); } else { // Message Recieved echo(" <div class=\"chatbubble-recieved\"> <div class=\"chatbubble-person\">".$vardump['contact'][0]['name']."</div> <p>".$message['message']."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $message['date'] / 1000)."</div> </div> "); } // Reset our $last_messge_stamp variable $last_message_stamp = $message['date']; } I should also add that I am using the following queries to pull this date out of my database... Code: [Select] $sql_get_messages = "SELECT * FROM messages WHERE thread_number LIKE '%$the_thread%' ORDER BY epoch_date ASC"; $sql_get_calls = "SELECT * FROM calls WHERE number LIKE '%$the_thread%' ORDER BY datetime ASC"; $sql_get_contact = "SELECT * FROM contacts WHERE number LIKE '%$the_thread%' LIMIT 1"; But, I feel that this is horribly inefficient, and it doesn't work right... I only ever get a single call dumped. What am I doing wrong? Specific question with general application here. i am having some trouble with a loop and am getting some odd timing results specifically this is a WMI query on a hyper-v server retrieving disk information but im not sure the context of the query is relevant here. The main question is how come the first iteration of the loop is so much slower than the other iterations, it just doesnt seem to make sense to me unless ive done something stupid here i cannot see. any ideas ? Code: [Select] <?php $diskstart = microtime(true); // get the hard disk size try { $resultDisk = $wmi->ExecQuery("SELECT BlockSize,NumberOfBlocks FROM msvm_LogicalDisk where systemname like '%" . $guid . "%' and name='Hard Disk Image'"); $ct=0; $start1 = microtime(true); $start = microtime(true); foreach($resultDisk as $itemDisk) { $end = microtime(true); echo "<BR>FOREACH: [" . Round($end-$start,3) . "] seconds"; $vm[$name]['disks'][$ct] = ($itemDisk->BlockSize * $itemDisk->NumberOfBlocks)/1024; // format the disk size into KB $ct++; $start = microtime(true); } $end1 = microtime(true); echo "<br> ALLLOOP: [" . Round($end1-$start1,3) . "] "; } catch(exception $e) { } $diskend = microtime(true); echo "<br>DISK: [" . ($diskend-$diskstart) . "] seconds"; ?> and here are the results Code: [Select] FOREACH: [1.236] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.002] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds ALLLOOP: [2] DISK: [2.1837468147278] seconds I have an array of property details that prints to the page. Later on that same page, I would like to use one of the array's values as part of a mailto script, but I can't seem to figure out how to recall it. could someone point me in the direction of how I can make the array's values available for later use? I hope this is clear enough. Thanks Evening everyone and Merry X-Mas (Happy Holidays) or whatever fits you best.... I have been trying over and over for about 12 hours to figure out how to get data from a specific JSON response and assign the specific values to a new array key/value pair. The various ways I have tried to figure this out are numerous so i'm going to avoid the runnig list of "I trieid this...and this...and this... etc etc." just understand I have reached a dead end point where I need help badly.
Here is what our end goal is:
"The company" is a "service industry" provider (plumbing, electrical etc. etc.) who wants to dispatch its technicians to new jobs based on which technician has the shortest travel time from any existing address where they already have a scheduled appointment that day and has available time in there schedule. Thus the dispatching system when a new service call is entered is going to give "recommended" technicians (up to 4) to be assigned the new service call based on the above mentioned criteria. (Efficient routing to save company gas cost)
1.) We have a "New service" street address assigned to the $to variable: $to = "4813 River Basin Dr S, Jacksonville FL 32207"; 2.) We will have "records" array which containes a series of records, each record consists of a ticket# a technician id# and a street address: $records = array( array("DV1012","30453423","9890 Hutchinson Park Dr Jacksonville, FL 32225"), array("DB3434","30404041","821 Orange Ave Crescent City, FL 32112"), array("DB3434","30605060","1972 Wells Road, Orange Park FL 32073"), array("DB4578","30605060","2 Independent Drive, Jacksonville FL 32202"), array("DB7841","30605060","5000 Norwood Avenue, Jacksonville FL 32208"), array("DB3235","30605060","9501 Arlington Expressway, Jacksonville FL 32225"), array("DB7894","30605060","Massey Avenue, Jacksonville, FL 32227"), array("DB2020","30121212","11200 Central Pkwy Jacksonville, FL 32224") ); 3.) We are going to prepare the records array for submission to Google's Distance Matrix API by URL encoding each array value into a single variable and then submit it: foreach ($records as $key => $value) {$from = $from.urlencode($value[2])."|";} $to = urlencode($to); $data = file_get_contents("//maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&units=imperial&mode=driving&sensor=false"); $res=json_decode($data) or die("Error: Cannot read object"); You may look at the ACTUAL live Google response from this he http://tiny.cc/i6eerx (We have applied <pre> and var_dump($res) to the output) We are looking to get the following information back: The distance and travel time between the "New Service" address ($to) and each of the address' in the $records array ($from), now once that information is returned from Google (JSON response) we need to parse the response and narrow it down to 4 or less (Based on the 4 lowest drive times) to form a new array which ends like this: $results = array( array("DV1012","30453423","2.3 Miles","8 mins"), array("DB3434","30404041","2.8 Miles","9 mins"), array("DB3434","30605060","4.6 Miles","13.8 mins"), array("DB4578","30605060","5.7 Miles","15.2 min") ); OUR PROBLEM: Everything up until the the Google API response is fine, but iterating over the multidimensional arrays within multidimensional arrays of the JSON response is just not coming together in my head (or 2 dozen code attempts). I am able to ECHO an individual value like ( echo $res->rows[0]->elements[0]->distance->text; ) but this has no value for the end result i need to get to. My last thoughts and efforts was that that I was going to have to embed foreach statements within foreach statements to drill down through the various arrays but that hasn't worked very well and it seems like it shouldn't be how it has to be done. I would appreciate any help in showing me how the iteration code should be written and any explanation about the code so i can wrap my head around it. Hi, I have a web site that sells both video and images. The full versions are located securely behind a paywall, however in a bid to get visitors to purchase them and to promote the members offering I have trailer videos of 30 seconds to one minute and four free images per imageset. I want to be able to restrict the number of images a visitor can view for free to 12 and the number of videos a visitor can play to 5. With a little graphic/overlay notifying the user when they have exceeded their free play/preview limit. I have been advised that a tracking cookie and php if statement would be the way to go to achieve this. I have got a cookie that is successfully logging views that is written to on a free preview link as an onclick function. I have tried writing some php if code that will have the normal thumbnail or video divs display as usual if the views recorded in the cookie are below 12 or five, respectively, and have a not allowed, please subscribe div that would show over the thumbnails or video divs should the number of views exceed the threshold. My PHP code does not seem to be working at all, I have ran it through an online syntax checker - corrected the mistakes and now it's supposed to be working but opts to display nothing instead of either if argument. Videos then become a whole other problem because at the moment I have no other way to track the view/visit other than to count the loading of the video summary page with the free player as the preview, whether or not the clip is played - ideally I would like the view to be counted when the video begins to play. But I have no idea how to write to the cookie from Flash (is that even possible?) Any help would be greatly appreciated. Here is my situation. I have an exam application built in Flash, where after the taker is finished and submits their scores a record is created in MySQL in a log table. Basically there is a column called attempt which is populated with a 1 after they have successfully finished the exam. When this column has a 1, the user is locked out and cannot access the exam when they try and login. The Flash part was built a while back in AS3 and is very cumbersome to try and figure out and make changes, so I have been trying to improve some things on the PHP/MySQL end. What I have now is a php based login which uses if else statements to determine if a user has passed and if they have not uses a DELETE statement to delete their log record and thus they regain access to taking the exam. Code below. <?php if(($pcnt[$i]*100) > 89) { echo "<span class='green'>you did great!</span>"; } else { $query_delete = "DELETE FROM log_March2011 USING log_March2011 INNER JOIN roster_March2011 WHERE log_March2011.user_id =roster_March2011.user_id AND roster_March2011.user_id = '{$_SESSION['user_id']}'"; //echo $query_delete; //for debugging test $result_delete = mysql_query($query_delete) or trigger_error('Query failed: ' .mysql_error()); //$num = mysql_affected_rows($db); if ($result_delete) { echo "<span class='red'>Please review missed questions/sections below</span><br />You can now retake the exam"; }// end if else { echo "No record of taking exam"; } //end else } ?> what I would like to do to improve the application is to be able to implement a set number of attempts allowed before the user is disallowed to take the exam again, but not sure how to implement this or is even possible? Hey.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong>" round($courseMark) "<strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys I am working to echo the results in a while or for loop... Both of my sample codes work, but the results are wrong! The while loop ONLY echos a result IF the first record in the postings table matches the id passed (does not display a result unless the first record has a match) The if loop displays ALL listings with the same name (counts them all) so there are no unique listings! <?php $posts_by_city_sql = "SELECT * FROM postings WHERE id='$_GET[id]'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); /* While Loop */ while($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } /* For Loop */ $posts_by_city_row = mysqli_fetch_array($posts_by_city_results); for ($i=0; $i<sizeof($posts_by_city_row); $i++) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } ?> Results with for loop (there are 7 total unique book names, but it's just counting the first match on id 7 times like below): AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners |