PHP - Returning Arrays In Loop
I'm trying to create a series of functions, when activated:
a. scans a target directory for jpg's -> returns file names to an array b. takes those file names and stripes the .jpg from them -> return file name, extension, and full filename c. inserts said file names into a MySQL database Here's the problem: The second function won't loop on the return array('name' => $name), it just does it once. Code: Function 1 (of 3) Code: [Select] function scanJpg($phpath){ $dir = opendir($phpath); while(false !== ($file = readdir($dir))){ if($file != "." && $file != ".."){ if(!is_dir($phpath.$file)){ $results[] = $file; } } } closedir($dir); return $results; } // returns // Array ( [0] => lakeonrefuge.jpg [1] => shasta04.jpg [2] => carly_lol.jpg [3] => beach_adventures_florence.jpg [4] => beach_adventures.jpg [5] => Beach-0168.jpg ) function 2 Code: [Select] function stripJpg($jpgs,$phpath){ foreach($jpgs as $jpg){ $ext = strrchr($jpg, '.'); if($ext !== false) { $name = substr($jpg, 0, -strlen($ext)); echo $name."<br />"; echo $jpg."<br />"; echo $ext."<br /><br />"; return array( 'name' => $name, 'filename' => $jpg, 'ext' => $ext ); } } } ## $jpgs = scanJpg($phpath); ## print_r(stripJpg($jpgs,$phpath)); ## ## returns the following ## Array ( [name] => lakeonrefuge [filename] => lakeonrefuge.jpg [ext] => .jpg ) What am I overlooking? Thanks in advance! Similar TutorialsHello, Hope someone can help me cause i been at it all day and google woul'dn't help me. I been writing a little script which generates a list of numbers you can check and make a list of the numbers that have been checked. Now when i use $_get to the next page everything works but now i need to take the url and use $_get back to the generated check box list and it needs to know by the url which box had been checked and checked that one so the list can be altered. here is my code sofar Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>AH plaatjes.</title> </head> <body name="top"> Meer info beneden aan de pagina. <a href="#beneden">Naar beneden.</a> <p> <script language=JavaScript> function set(n) { temp = document.form1.elements.length ; for (i=0; i < temp; i++) { document.form1.elements[i].checked=n; } } function checkall() { void(d=document); void(el=d.getElementsByName('check')); for(i=0;i<el.length;i++) void(el[i].checked=1) } //invert function invers(){ temp = document.form1.elements.length ; for (i=0; i < temp; i++){ if(document.form1.elements[i].checked == 1){document.form1.elements[i].checked = 0;} else {document.form1.elements[i].checked = 1} } } </script> </p> <form id="form1" name="form1" method="get" action="./readlist.php"> <label>Naam eigenaar lijstje:<input name="naam" type="text" /></label> <label>Lijst van selectie plaatjes<select name="collect"> <option value="0">selecteer optie!</option> <option value="1">in decollectie</option> <option value="2">nog niet in collectie</option> <option value="3">dubbele collectie</option> </select></label> <p> <?php //TO Do trying to get the checkboxes checked with get and array ///////////////// do { $i = $i+1; echo " <input type=\"checkbox\" name=\"checked[]\" id=\"check\" value=\"". $i ."\"/> <label for=\"". $i ."\">". $i ."</label> <br /> "; if($i > 324){break;} }// end do while($i < 325); ?> </p><input name="check" type="submit" value="Print lijst" /> <input type=button onClick="checkall()" value="selecteer alles" name="button"> <input name=button onclick="invers()" type=button value=" Keer selectie om "> <INPUT name=button onclick=set(0) type=button value=" Reset "> </form> <p><a name="beneden">De geselecteerde nummers komen overzichtelijk in een lijstje. Zo heb je heel overzichtelijk een lijst met de nummers die je al hebt of juist nog niet hebt. Die kan je dan doorsturen selecteren en kopieren met je rechtermuis knop en naar je kennissen of vrienden sturen.</a> ook kan je de url (webadres) kopieren en doorgeven.</p> <p><a href="#top">Naar boven.</a></p> </body> </html> Now what i need is when you fill out an url like http://localhost/ah/index.php?checked%5B%5D=2&checked%5B%5D=3 it needs to check the same boxes. please help me out thanks in advance I'm having troubling with trying to create a function to spit out a single array with the following array. I can write it in a away that looks through the arrays manually. the results i am trying to generate is that each item in generated array. Array to convert array( "account" => array( "login", "register", "logout", "edit", ), "p" => array( "report", ), "array1.0" => array( "array2.0" => array( "array3.0", "array3.1 ), "array2.1", ), generating the array will look like this
Array ( [0] => account [1] => account/login [2] => account/register [3] => account/logout [4] => account/edit [5] => p [6] => p/report [7] => array1.0 [8] => array1.0/array2.0 [9] => array1.0/array2.0/array3.0 [10] => array1.0/array2.0/array3.1 [11] => array1.0/array2.1 ) The idea is that id generates a single array with combined labels and arrays inside, etc. I just can't figure out how to create a script that will create this array even If I add a new value or array.
Hey Guys. I have a custom function that simply loops through an array and outputs the menu categories it finds in the array.
The foreach loop passes the function an array and the function returns the the value. The problem is that the function returns that last value.
Now I know some of you might say ... "Why don't you put the foreach inside the function and return the value when the foreach loop has been completed"
The reason why is because I to use that foreach loop through another function as well. I was thinking about using globals to get the return value. But just wanted to get your perspective on the best option here.
Please let me know what you guys think Thanks
User Defined Function
function displayMenuCategories($menu_category){ $display_menu =""; $category_id = $menu_category['menu_cat_id']; $display_menu .= "<div class='menu_cat'>{$menu_category['menu_cat_name']}</div><br>\n"; if(!empty($menu_category['menu_cat_desc'])) { $display_menu .= "<div class='menu_desc'>{$menu_category['menu_cat_desc']}</div>\n"; } $category_info = array("display" => $display_menu, "category_id" => $category_id ); return $category_info; }Foreach loop $left_menu_categories // Is the array that contains all the menu categories foreach($left_menu_categories as $left_menu_category){ $get_categories = displayMenuCategories($left_menu_category); } var_dump($get_categories); Edited by eldan88, 06 July 2014 - 05:01 PM. I have this query which query the parent.name and the node.name as well. Code: [Select] "SELECT parent.name FROM categories AS node, categories AS parent WHERE node.left_node BETWEEN parent.left_node AND parent.right_node AND node.name = '{$node_name}' ORDER BY parent.right_node AND node.left_node" below in the foreach loop is displaying both the node and parent, I only need the parent. I have done a little if statement saying that if node.name not to display but didn't work because both parent.name and node.name are displaying the he same field name. Code: [Select] <?php foreach($iterator as $key=>$value) { if($value <> "node.name") echo $value.'<br />'; } ?> I am trying to return all the photos in the database that has the albumid associated with that table info. I can echo the $album->id (albumid) no problem, but my query it think is somewhat off. Please anyone. Code: [Select] <div id="photo-items" class="photo-list-item"> <?php echo $album->id.'<br>'; // fetch album photos and ids $database =& JFactory::getDBO(); $query = "SELECT * FROM jos_photos where albumid = ".$album->id." ORDER BY ASC"; $photos = mysql_query($query); //This returns and array of photos, but then needs to display all the photos in loop below, but it not retuning none, even if there is 100 photos in table and in the folder directory if($photos) { for( $i=0; $i<count($photos); $i++ ){ $row =& $photos[$i]; ?> <div class="photo-item" id="photo-<?php echo $i;?>" title="<?php echo $this->escape($row->caption);?>"> <a href="<?php echo $row->link;?>"><img class="" src="<?php echo $row->getThumbURI();?>" alt="<?php echo $this->escape($row->caption);?>" id="photoid-<?php echo $row->id;?>" /></a> <?php if( $isOwner ) { ?> <div class="photo-action"> <a href="javascript:void(0);('<?php echo $row->id;?>');" class="remove"><?php echo JText::_('CC REMOVE');?></a> </div> <?php } ?> </div> <?php } } else { ?> <div class="empty-list"><?php echo JText::_('CC NO PHOTOS UPLOADED YET');?> <button class="button button-upload" href="javascript: void(0);&userid=88" id="upload-photos-button">Start Uploading</button></div> <?php } ?> </div> When using cURL, how would I be able to include a call inside my get_all that basically will loop through all the next_page, get and store the data and then output it to $response->data when the "next_page" parameter becomes null? **Here is the method**: public function get_all() { return $response->data; } **This is what $response->data is returning as of now** (The cURL code wasn't included here): "paginator": { "total": 3092, "per_page": 500, "current_page": 2, "last_page": 7, "prev_page": "https://oc.com/api/v1/employees/?page=1", "next_page": "https://oc.com/api/v1/employees/?page=3" }, "data": [ { "id": 1592, etc.... Here are all of my unsuccessful attempts: public function get_all() { // $next_url = $response->paginator->next_page; // // foreach ($response as $next => $next_page) { // print_r2($next); // // if ($next_url !== null) { // $next_page = $response->data; // } // } // foreach ($response as $paginator => $next_page) { // if ($next_url !== null) { // $return[] = $response->data; // } // } // var_dump($response->paginator); // if ($next_url !== null) { // $this->get_all($path, $args, $next_url); // } return $response->data; } Edited October 30, 2019 by Sema314 this is only returning one record, when I know there are more, and it's an endless loop crashing my browser, can someone tell me how my brackets are wrong, or what is wrong? Code: [Select] if (isset($_POST['search'])){ $keyword=$_POST['keyword']; } $sql="SELECT id, fname, lname FROM obituaries WHERE lname LIKE '%$keyword%' OR fname LIKE '%$keyword%' ORDER BY id DESC"; $results = mysql_query($sql); $num = mysql_num_rows ($results); if ($num > 0 ) { $i=0; while ($i < $num) { $id = mysql_result($results,$i,"id"); $fname = mysql_result($results,$i,"fname"); $lname = mysql_result($results,$i,"lname"); ?> <a href="view.php?id=<?php echo ($id); ?>"><?php echo($fname); ?> <?php echo($lname); ?></a> <?php } } ?>Thanks in advance Hello all, I'm new to PHP and new to this forum (although I have benefitted from your help already -cheers!). However, this time I cannot find the answer I need/recognise/understand.. I have a form and want to conduct tests on each field returning an error message as a session variable if the test fails. The test will be different for some of the fields, and the error message is specific to each field. If there is an error in any one of the fields I want to be redirected to a failure page where all of the error messages are displayed, otherwise I am sent on to another page. I have already written and tested a function to sanitise the incoming form data, so that's not a problem - it's just how to loop through and test. I can guess that there are many ways to do this but I need to understand why one option is better than another, and follow the syntax used (it's all part of my steep learning curve) The approach I have thought to use is to create an array holding the field name, the test and the message, then loop through using foreach, applying the array values into the test and creating the error message....but it's not working for me. The other method is to declare a variable $Stop='No' and if the loop identifies an error, part of the output is to change this to 'yes' and through that redirect to the error page. I'd really welcome your advice and tuition....cheers.. my code so far is... Code: [Select] $Stop='No'; $StaffPassCheck=sanitisealphanum($_POST['PasswordCheck']); $Errors[0]['value']= sanitisealphanum($_POST['FirstName']); $Errors[0]['message']='Please re-enter your name'; $Errors[0]['test']=($StaffFname=""); $Errors[1]['value']= sanitisealphanum($_POST['Surname']); $Errors[1]['message']='Please re-enter your surname'; $Errors[1]['test']=($StaffSname=""); $Errors[2]['value']= sanitisealphanum($_POST['Post']); $Errors[2]['message']='You must select an option'; $Errors[2]['test']=($StaffPost="Select Value"); $Errors[3]['value']= sanitisealphanum($_POST['Username']); $Errors[3]['message']='You must select an option'; $Errors[3]['test']=($StaffUser=""); $Errors[4]['value']= sanitisealphanum($_POST['Password']); $Errors[4]['message']='Please re-enter your password'; $Errors[4]['test']=($StaffPass=""); $Errors[5]['value']= sanitisealphanum($_POST['PasswordCheck']); $Errors[5]['message']='Sorry, your passwords do not match'; $Errors[5]['test']=($StaffPass===$StaffPassCheck); foreach ($Errors as $key => $Value){ if ( $Errors['test']=true ){ $Stop='Yes'; return $_SESSION[$key]=$Value['message']; } } if ($Stop='Yes'){ header('Location.test.php'); die(); }else{ header('Location.indexp.php'); } How to use both Code: [Select] $matchInArray[$i] and Code: [Select] $matchInArrayR[$i] arrays work within the same loop? my code: $matchInArray = array($match1, $match2, $match3, $match4); $matchInArrayR = array($matchresult1, $matchresult2, $matchresult3, $matchresult4); if($getawayr='Group A'){ $numWins = 0; for($i=0; $i<9; $i++){ if($matchInArray[$i] == "W" && $numWins < 3){ $matchInArrayR[$i] = "Qualified for Semi Finals"; $numWins++; } } } Hi everyone, If you take a look at my code below I am having trouble echoing the key/ value pair of the 'sex' array which is a sub array of 'pens'. I have tried so many different ways but to no avail, thanks Chris! Code: [Select] <?php $products = array( 'paper' => array( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers", 'sex' => array ( 'condom' => "Protection")), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips") ); echo "<pre>"; foreach ($products as $section => $items ) foreach ($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> I have two arrays as Code: [Select] $array1=array("word1","word2","word3"); $array2=array("term1","term2","term3"); How can I have a foreach loop to echo "word1-term1", "word2-term2", .... I mean having Code: [Select] echo "$array1[0]-$array2[0]";but in a foreach loop Hi, This problem has been driving me crazy all day. I am relatively new to PHP. I basically am trying to populate a database with data from site users. I am using session variables to store their data temporarily as they navigate through the sign up process. A user will input how many 'categories' they wish to populate on page 1. Page 2 will then ask them to specify the details of each category. Eg Category 1: Title, Description, Amount. Category 2: Title, etc. So far I have been able to do this, I now want to store what they have input in session variables. My thoughts were to take the number of categories they have sepcified and create that number of arrays using a loop. Each array will store the details on each category. My code is as follows: Code: [Select] $count=$_POST['count']; //Get how many categories were added //Create an array for each category for ( $counter = 0; $counter <= $count; $counter++){ ${'Categoryarr'.$counter} = array(); }; for ( $counter = 0; $counter <= $count; $counter++){ $Categoryarr[$counter][1]=$_POST['amount_'.$count]; $Categoryarr[$counter][2]=$_POST['desc_'.$count]; $Categoryarr[$counter][3]=$_POST['title_'.$count]; }; When I output the code, I seems to have created the specified number of arrays, but has populated all of them with the same data from the last category. Does anyone know where I am going wrong? Thanks, Bernard Let me explain my problem. I have an array with dates and numbers in format ($cronograma) Ex: Array ( [2020-09-21] => Array ( [0] => 2020-09-21 [1] => 2 [2] => 2 [3] => 2 ) [2020-09-28] => Array ( [0] => 2020-09-28 [1] => 2 [2] => 2 [3] => 4 ) Then i have another array with 2 ids (in this case 58,60) ($id) Finally i have a third array with numbers only (in this case 34,34) $tot So what i want is cross information beween them, for example for id 58 I must get dates (first element and last element when $tot = 34) for id 60 I must get dates (first element after $tot =34 and last element of array) Whath i have so far is this foreach ($id as $idPlan) { foreach ($cronograma as $c) { $t1 = 0; foreach ($tot as $d) { $t1 += (int)$d['tempos']; if ($c[3] == $t1) { $newAr[] =$idPlan; $newAr[] = $c[0]; } } } } My response array(8) { [0]=> string(2) "58" [1]=> string(10) "2021-02-01" [2]=> string(2) "58" [3]=> string(10) "2021-06-14" [4]=> string(2) "60" [5]=> string(10) "2021-02-01" [6]=> string(2) "60" [7]=> string(10) "2021-06-14" } null So it's clear that i have all repeated I should have a line like: 58 - 2020-09-21 -2021-02-01 Any help? I have two arrays, X and Y, which contain names. The arrays are of the same size. The arrays are related to each other such that for each pair X[n] , Y[n] X is friends with Y. For example: X[0,1,2] = [Link, Cloud, Cloud, Mario, Mario, Luigi] Y[0,1,2] = [Zelda, Barrett, Tifa, Luigi, Bowser, Mario] Link is friends with Zelda Cloud is friends with Barrett and Tifa Mario is friends with Luigi and Bowser Luigi is friends with Mario I want to loop through these arrays and, for each unique name, find all of that person's friends. I then want to print the results to a text file, like so: Link, Zelda Cloud, Barrett, Tifa Mario, Luigi Luigi, Mario I know how to do this theoretically, but I just need help with the PHP syntax. Thanks very much. Hi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. I have this thing that i am trying to make but i cant get it to work.. can anyone help? Code: [Select] function sql_read( $dbname,$dbusername,$dbpassword ) { $names = array(); $password = array(); $connect = @mysql_connect("mysql11.000webhost.com",$dbusername,$dbpassword) or die("Could Not Connect"); @mysql_select_db ($dbname) or die("Could not find DataBase"); $query = mysql_query("select * from users"); $numrows = mysql_num_rows($query); if ($numrows > 0){ while($row = mysql_fetch_assoc($query)){ $names[] = $row["uname"]; $password[] = $row["password"]; $id = $row["id"]; } $return = array($names,$password,$id); }else{ $return = array(); } return $return[]; } $names = array(); $names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0]; The error i get is Code: [Select] Parse error: syntax error, unexpected '[' in /home/a5480952/public_html/sql/index.php on line 28 Line 28 is "$names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0];" Please help... i REALLLLD need help with this.. ask questions if you want to know more about what i am trying to do... thanks! 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? I have two arrays, both with the same key values. I'd like to combine them. So for instance... Code: [Select] <?php $array1['abcd'] = array( 'value1' => "blah", 'value2' => "blahblah"); $array1['efgh'] = array( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz"); $array2['abcd'] = array('value3' => "three", 'value4' => "four"); $array2['efgh'] = array( 'value3' => "hohoho", 'value6' => "six6"); function combine_arrays($array1,$array2) { //*combining* return $single_array; } echo "<pre>"; print_r(combine_arrays($array1,$array2)); echo "</pre>"; /* would produce ['abcd'] = ( 'value1' => "blah", 'value2' => "blahblah", 'value3' => "three", 'value4' => "four" ) ['efgh'] = ( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz", 'value3' => "hohoho", 'value6' => "six6" ) */ ?> What's the easiest way to do this? 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? |