PHP - Break Out Of Nested Foreach..
Hi,
I'd like to know what the best way of breaking out of a nested foreach loop is..but not breaking out of the first foreach ears the code like, Code: [Select] foreach ($apts as $apt) { foreach($rdb as $rem) { // Check to see if we've already sent a reminder for this appointment if($apt->id == $rem->appid) { // TODO get out of this foreach and go to the next iterartion of the first foreach } } //rest of 1st foreach code here } is there some syntax i can put at the first foreach eg [here] and reference it within the second foreach continue[here]; or something? thanks, Similar TutorialsHey all, I'm wondering the best way to use foreach to break a list of records into groups. For example, the problem with this: Code: [Select] foreach($vanity_url as $v){ if($v->approved){ echo "Approved vanity urls:"; echo $v->url; } else { echo "Unapproved vanity urls:"; echo $v->url; } } is it will return this: Code: [Select] Approved vanity urls: michellefrancis Unapproved vanity urls: johnmerlino Unapproved vanity urls: ericmayers when I want it to return this: Code: [Select] Approved vanity urls: michellefrancis Unapproved vanity urls: johnmerlino ericmayers thanks for response Hey all, I have two objects that contain object instances. I want to compare the properties of the instances and if the old_parent's property doesn't exist as one of the $new_parent's property, then I place the old_parent's property in an array called unneeded_ids. Problem is when I use nested foreach to loop through the instances of the two objects, despite old_parent having only one instance with a property id of 1, because it loops twice, the array gets two "1" values rather than just one: Code: [Select] public function update(){ $vanity_url = new VanityUrl(); $vanity_url->where('user_id',$this->current_user()->id)->get(); $zones = $this->input->post('zones'); $zone = new Zone(); $zone->where_in('name', $zones)->get(); $subcategory = new Category(); $subcategory->where('id',$this->uri->segment(4))->get(); $old_parents = new Category(); $old_parents = $subcategory->related_category->get(); $unneeded_ids = array(); if(!$this->input->post('catupload')){ if($subcategory->save($zone->all)){ redirect("blogs/$vanity_url->url/categories"); } else { echo "Error occurred. Please try again."; } } else { $new_parents = new Category(); $controller = $this->input->post('catupload'); $new_parents->where_in('controller',$controller)->get(); foreach($new_parents as $new){ foreach($old_parents as $old){ if($new->id != $old->id){ array_push($unneeded_ids, $old->id); } } } var_dump($unneeded_ids); } } The var_dump outputs: Code: [Select] array(4) { [0]=> int(126) [1]=> int(127) [2]=> int(126) [3]=> int(127) } but it should only output: Code: [Select] array(2) {[0]=> int(126) [1]=> int(127)} That's because there's only one object instance of old_parent that has a property id value of 126 and the same for 127. The nested for each loop is causing it to iterate twice against the same object and sticking it into the array. How do I get desired result? Thanks for response. This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } I'm trying to figure out how I can break a string down if the strings length is longer then lets say 140 characters including white space. At first I was figuring maybe maybe I could do something with explode or implode after I get a get my strings length but the string in question has no static values to them that would let me break it apart or put it back together. Now In most cases I would use substr() to return my 140 characters, however I need to take 140+ and make an array of the extra so I can run a for each on it. I am using this for an SMS app I am helping develop. I know I can limit my the output to only 140, just based on the notion that a single SMS is capped at 140-160 on most carriers. Unfortunately for me thats not the case so I need to break this apart and I am stumped, anyone got any ideas? How can i break down strings for example i have a simple search database for products where as a user searches a term this can be one, two three words and so on. I'm using a wildcard; but i want the best way to get the possible search so i would like to break down the string into separate words and then use that to search the database using wildcards is this possible? Thanks for reading. I have a chain of methods, is there anyway to end the chain half way through if some particular event happens? Here is an example (not the best but still an example): Code: [Select] <?php $age = $class->post("age")->callback(funciton(){ global $class; if($class->string() < 18){ // end the execution of the chain, doesn't execute toInt() } })->toInt(); ?> Good morning, I passed a bunch of HTML tags over a function that delete then, keeping just the text between. The problem is, after that all the tags were replaced by line breaks. Something like this before the function: <tr> <td> Text </tr> </td> After the function the 4 tags were correctly removed but instead i receive just the string "Text" I receive 2 line breaks, the "Text" and other 2 line breaks, like this: Text In HTML code this line breaks has no tags like <br> or <p> it's just blanck lines. I need to get just the text, how can I get rid of then? I tried this and also didn't work. $text = str_replace("/n", "", $text ); Thanks Danilo Jr. hi i have some troubles to create a new line break for this code: i already tried: Code: [Select] echo "<input type='radio' name='gropu1' value='$id'>$data \n "; // Code: [Select] echo "<input type='radio' name='gropu1' value='$id'>$data.\n "; // Code: [Select] echo "<input type='radio' name='gropu1' value='$id' >$data.'\n'"; what is the correct syntax for that? I was wondering if you guys could help me 'break' a function I've been working on. It converts a CSV-formatted string to a 2d array following RFC4180. Here's the function. /** * * Covert a multi-line CSV string into a 2d array. Follows RFC 4180, allows * "cells with ""escaped delimiters""" and multi-line enclosed cells * It assumes the CSV file is properly formatted, and doesn't check for errors * in CSV format. * @param string $str The CSV string * @param string $d The delimiter between values * @param string $e The enclosing character * @param bool $crlf Set to true if your CSV file should return carriage return * and line feed (CRLF should be returned according to RFC 4180 * @return array */ function csv_explode( $str, $d=',', $e='"', $crlf=TRUE ) { // Convert CRLF to LF, easier to work with in regex if( $crlf ) $str = str_replace("\r\n","\n",$str); // Get rid of trailing linebreaks that RFC4180 allows $str = trim($str); // Do the dirty work if ( preg_match_all( '/(?: '.$e.'((?:[^'.$e.']|'.$e.$e.')*+)'.$e.'(?:'.$d.'|\n|$) # match enclose, then match either non-enclose or double-enclose # zero to infinity times (possesive), then match another enclose, # followed by a comma, linebreak, or string end | ####### OR ####### ([^'.$d.'\n]*+)(?:['.$d.'\n]|$) # match anything thats not a comma or linebreak zero to infinity # times (possesive), then match either a comma or a linebreak or # string end )/x', $str, $ms, PREG_SET_ORDER ) === FALSE ) return FALSE; // Initialize vars, $r will hold our return data, $i will track which line we're on $r = array(); $i = 0; // Loop through results foreach( $ms as $m ) { // If the first group of matches is empty, the cell has no quotes if( empty($m[1]) ) // Put the CRLF back in if needed $r[$i][] = ($crlf == TRUE) ? str_replace("\n","\r\n",$m[2]) : $m[2]; else { // The cell was quoted, so we want to convert any "" back to " and // any LF back to CRLF, if needed $r[$i][] = ($crlf == TRUE) ? str_replace( array("\n",$e.$e), array("\r\n",$e), $m[1]) : str_replace($e.$e, $e, $m[1]); } // If the raw match doesn't have a delimiter, it must be the last in the // row, so we increment our line count. if( substr($m[0],-1) != $d ) $i++; } // An empty array will exist due to $ being a zero-length match, so remove it array_pop( $r ); return $r; } And to use it: $csv = 'this,will,"be ""separated""",by "commas,",,"should work with ""multiline,"", ",entries some,last,data,"test"'; print_r( csv_explode($csvn) ); or $csv_eurwin = "this;will;'be ''separated''';by\r\n"; $csv_eurwin .= "'semicolons;';;'should work with\r\n"; $csv_eurwin .= "''multiline;'';';entries\r\n"; $csv_eurwin .= "some;'last';data;'test'"; print_r( csv_explode($csv_eurwin, ';', '\'', TRUE) ); Thanks! Here's the actual spec if anyone cares Code: [Select] 1. Each record is located on a separate line, delimited by a line break (CRLF). For example: aaa,bbb,ccc CRLF zzz,yyy,xxx CRLF 2. The last record in the file may or may not have an ending line break. For example: aaa,bbb,ccc CRLF zzz,yyy,xxx 3. There maybe an optional header line appearing as the first line of the file with the same format as normal record lines. This header will contain names corresponding to the fields in the file and should contain the same number of fields as the records in the rest of the file (the presence or absence of the header line should be indicated via the optional "header" parameter of this MIME type). For example: field_name,field_name,field_name CRLF aaa,bbb,ccc CRLF zzz,yyy,xxx CRLF 4. Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file. Spaces are considered part of a field and should not be ignored. The last field in the record must not be followed by a comma. For example: aaa,bbb,ccc 5. Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example: "aaa","bbb","ccc" CRLF zzz,yyy,xxx 6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example: "aaa","b CRLF bb","ccc" CRLF zzz,yyy,xxx 7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example: "aaa","b""bb","ccc" why is it that when i saved it adds a break tag i dont understhand heres the code i cant find it its only when i save or remove a video and save it it has a break Code: [Select] <?php require "scripts/connect.php"; if($_POST['submitbtn']){ $video1 = mysql_real_escape_string(html_entity_decode($_POST['video1'])); $video2 = mysql_real_escape_string(html_entity_decode($_POST['video2'])); $video3 = mysql_real_escape_string(html_entity_decode($_POST['video3'])); $video4 = mysql_real_escape_string(html_entity_decode($_POST['video4'])); if($video1){ if($video2){ if($video3){ if($video4){ $query = mysql_query("UPDATE videos SET video1='$video1',video2='$video2',video3='$video3',video4='$video4'"); header("location: http://www.mywebsite.com/admin/editvideos"); }else $msg = "PLEASE FILL IN"; }else $msg = "PLEASE FILL IN"; }else $msg = "PLEASE FILL IN"; }else $msg = "PLEASE FILL IN"; } mysql_close(); ?> <?php include "header.php";?> <?php if($email){?> <?php include "inc/nav.php"; ?> <div id="righthomecontent"> <?php require "scripts/connect.php"; $query = mysql_query("SELECT * FROM videos"); $rows = mysql_fetch_assoc($query); $video1 = stripslashes($rows['video1']); $video2 = stripslashes($rows['video2']); $video3 = stripslashes($rows['video3']); $video4 = stripslashes($rows['video4']); mysql_close(); ?> <center>MUST USE THIS IN VIDEOS ?wmode=opaque"</center><br> <center>All videos are Width='220' and Height='240'</center><br> <form class="editvideoform" action="editvideos" method="post"> <table> <tr> <td></td> <td><?php echo $msg;?></td> </tr> <tr> <td>VIDEO 1</td> <td><textarea cols=25 rows=10 name="video1"><?php echo $video1;?></textarea></td> </tr> <tr> <td>VIDEO 2</td> <td><textarea cols=25 rows=10 name="video2"><?php echo $video2;?></textarea></td> </tr> <tr> <td>VIDEO 3</td> <td><textarea cols=25 rows=10 name="video3"><?php echo $video3;?></textarea></td> </tr> <tr> <td>VIDEO 4</td> <td><textarea cols=25 rows=10 name="video4"><?php echo $video4;?></textarea></td> </tr> <tr> <td></td> <td><input type="submit" name="submitbtn" value="SUBMIT" /></td> </tr> </table> </form> </div> <?php } else { echo "<center><h1>PLEASE LOGIN</h1></center>"; } ?> <?php include "footer.php";?> echo '<div class="gamename">'.$values[0].'</div>'; echo '<div class="gameimage"><a href="'.$values[3].'"><img src="'.$values[1].'"></a></div>'; NOW i want 2nd echo under 1st echo. I tried every single <br> combination but no luck Also my 2nd question is: my image and link is a variable, it displays the image but there is something wrong with link. Variable is just like this www.mydomain.com\image\blabla.php but it shows link as==> www.mydomain.com\ instead of what i wrote above. I want to have a line break between the lastname and the age. Please help. echo $line["firstname"].' '.$line["lastname"].' Age is'.$line["age"].'!'; Hi all, I realised as users register themselves in the registration form, they wrote their comments and experience in the comment box which was provided Example (this is the content which they have written) 'Sentence 1 - Abccafsafsafafasdfafasfafs Sentence 2 - dasddsadsadsadsdaddsda' As you can see, between Sentence 1 and 2 there is a break (space). However when we store it in our database, and generate it out as a webpage, the break (space) is gone, and sentence 1 and 2 merged Example 'Abccafsafsafafasdfafasfafsdasddsadsadsadsdaddsda' My question is, how can we prevent 2 different sentences from merging? Thanks Below is my code and attached it what has been generated after we have posted it in webpage Code: [Select] cho '<div id="panel3">'; echo '<table>'; /***Tutor's Comments***/ echo'<div id="tutor_comments">'; echo '<br/><tr><td class="row_header">Tutor\'s Comments</td></tr>'; if (!empty($row2['tutor_comments'])) { echo '<tr><td>' . $row2['tutor_comments'] . '<br/><br/></td></tr>'; } /***Tutor's Commitments***/ echo '<tr><td class="row_header">Tutor\'s Commitment</td></tr>'; if (!empty($row2['tutor_commitment'])) { echo '<tr><td>' . $row2['tutor_commitment'] . '<br/><br/></td></tr>'; } /***Admin_comments***/ echo '<tr><td class="row_header">Admin\'s Comments</td></tr>'; if (!empty($row2['admin_comments'])) { echo '<tr><td>' . $row2['admin_comments'] . '<br/><br/></td></tr>'; } echo '</table>'; //End of Panel 3's table echo '</div>'; //End of tutor_comments DIV Code: [Select] $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].","; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } print $csv_output; I'm using the above to get a csv output in my browser, but it appears as a string of text eg a1,a2,a3,a4,b1,b2,b3,b4,... I'd like it to appear as a1,a2,a3,a4 b1,b2,b3,b4 c1,c2,c3,c4 Any ideas how? How do i get the first part of the string, all the way up until the string hits a line break? Code: [Select] <?php $string = "The quick red fox\n jumped over the brown\n lazy dog."; function first_of_string($str) { //php magic return $first_of_string; } echo first_of_string($string); //would produce "The quick red fox" ?> I think a switch break will help in this situation but I am definitely open to suggestions The problem I am have is that if there are 2 "Funner" or "Funnest" in the database then it displays duplicates in the in the column. I know that is what the code is telling it to do. If you look at the first row it should split them if there are 2 and display one in each column. In one time slot there is only allowed: - 1 Fun - 1 Funner or Funnest - 1 Funner or Funnest The case I am working with is there is 1 Fun and 2 Funners. The 2 Funners should split and display one in each "Funner/Funnest" column. There are planty of unique identifiers if someone has an idea for me. function taken($theType, $theTime){ $day_view = $_GET['date']; $DOP = explode("-", $_GET['date']); $topDOP = date("M", mktime(0, 0, 0, $DOP['1']))." ".$DOP['2'].", ".$DOP['0']; $dayDOP = date("l", mktime(0, 0, 0, $DOP[1], $DOP[2], $DOP[0])); connect(); $sql = "select * from party_times where dates = '$day_view' and paidID ='paid' and times = '$theTime'"; $result = mysql_query($sql) or die(mysql_error()); $day_count = mysql_num_rows($result); while($info = mysql_fetch_assoc($result)){ if($info['type'] == "$theType" && $info['times'] == "$theTime"){ $conID = "select DISTINCT confirmID from party_receipt where partyID = '".$info['partyID']."'"; $conqu = mysql_query($conID) or die(mysql_error()); while($con = mysql_fetch_assoc($conqu)){ $cid = $con['confirmID']; echo "<a href='party_booked.php?view=$cid'>RESERVED</a>"; }free($conqu); } }free($result); } Call the function: Code: [Select] <tr> <td width="25%"></td> <td width="25%" align="center">Fun</td> <td width="25%" align="center">Funner / Funnest</td> <td width="25%" align="center">Funner / Funnest</td> </tr> <tr> <td>11:00 AM</td> <td class = "res"><?php taken("Fun", "11:00 AM"); ?></td> <td class = "res"><?php taken("Funner", "11:00 AM"); ?></td> <td class = "res"><?php taken("Funnest", "11:00 AM"); ?></td> </tr> Thank you! so i have this string that i want to search on the database My database has 3 parts city, state, country and i have a string that is say "new york city, ny, united states" and i want to be able to be able to look into the database but search those three sections so for example "New York City" i would like to search under city "NY" i want it to search under state and "United States" i want to search under country so basically how can i split the string into those three sections?? hope someone can help me with this I'm trying to use SESSIONS, the start of my page looks like this: <?php session_start(); and the start of the source code looks like this: <br /> <b>Warning</b>: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent by The <?php tag is on line 1, yet as you can see Notepad++ seems to add a <br /> before it, which results in the sessions not working. How can I fix this? i am trying to build a payment gate way library do you think this is the best way of going about it requirements code to be flexible for different naming conventions to conform with standards not to break why i am thinking of doing it this way one application could have for addressline1 as add_1 while i different app will have it as add_line_1 $test2 = "yay"; $test = 'a:1:{s:6:"teatme";s:5:"test2";}'; // think of this a a db field $test = unserialize($test); echo"<pre style=\"text-align:left;\">"; print_r($test); echo"</pre>"; foreach ($test as $key => $value) { $test[$key] = $$value; } echo"<pre style=\"text-align:left;\">"; print_r($test); echo"</pre>"; please give us your thoughts |