PHP - Can I Put A Foreach Loop In A Function Before An <li> And The } After The </li>
ok.
say i have a list with a foreach loop in it. like this: Code: [Select] echo' <ul>'; $link = Link::find_all(); foreach($link as $links){ $name = $links->name; echo' <li>'.$name.'</li>'; } echo' </ul>'; now. say that i want to put this part : Code: [Select] $link = Link::find_all(); foreach($link as $links){ $name = $links->name; into a function so i can reuse the code... like this: FUNCTION Code: [Select] function(find_li){ $link = Link::find_all(); foreach($link as $links){ $name = $links->name; } Code: [Select] echo' <ul>'; find_li(); echo' <li>'.$name.'</li>'; } echo' </ul>'; the problem is the foreach } its not inside the function so the function will not work. but it needs to be after the </li> so that i get all the results in the <li> so is there a way to put the function before the <li> and the } after the </li> Similar TutorialsHello, I am new to PHP and have come to a grinding halt in my project. I am attempting to dynamically generate values for Wordpress shortcodes ( [example] ). I have successfully created the shortcodes and am having trouble setting their value. When I call the function that is supposed to return the value for the shortcode, it returns empty. I can however hard code a string and have it returned to the function, thereby manually creating a value for the shortcode. However, because the shortcodes are being generated and filled dynamically, I need this function to work without specific values. I know this may sound like a Wordpress specific question, but I have a feeling it's just my lack of understanding of PHP operations. So, here is the basic layout: The name of the shortcode is generated from within a foreach loop that retrieves the name of custom fields on the post ($keyName). Code: [Select] $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'myFields'); } The add_shortcode function has two parameters ('name_of_shortcode', 'function_name'): Code: [Select] add_shortcode((string)$keyName, 'myFields'); I need the myFields function to return the value of $fieldValue from within the foreach loop. That's where the problem lies. This doesn't work: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } This does work: Code: [Select] function myFields() { return 'Content to replace the shortcode'; } This code will replace [shortcode] with "Content to replace the shortcode" in the post. The ultimate goal is: when [$keyName] appears anywhere within the post, it will display the content returned by the myFields function ($fieldValue). However, it's not working. I can't seem to pass the value of $fieldValue to the myFields function and thereby return it to add_shortcode. Any help is appreciated and I am awaiting anxiously to answer any questions. Here's all the code together: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'yourFunction'); } 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 Hey guys, need help on some addition. foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(" "," ",$line))); if(stristr($login[1], "\n")) $login[1] = substr($login[1], 0, strlen($login[1])-2); $account_data[$line_num] = array($login[0], $login[1]); $UserID = $login[0]; $AuthKey = $login[1]; $MobLink = "http://mobsters-fb-apache-dynamic-lb.playdom.com/mob_fb/"; $RefreshStat = file_get_contents($MobLink."refresh_stat_manual?user_id=".$UserID."&auth_key=".$AuthKey); $Cash = explode ("<cash>", $RefreshStat); $Cash = explode ("<", $Cash[1]); $Cash = $Cash[0]; $CashForEcho = "$".number_format($Cash[0]); echo $CashForEcho."<br/>"; echo "<br/><br/>"; } The variable $Cash will be dynamic for each user I put in the $login_file, and I need to add all of those values up. So say I put in 3 users within the $login_file, and the $Cash for user 1 was $3,000, the $cash for user 2 was $6,000 and the $cash for user 3 was $1,000, I want to be able to automatically add them all up, so it would echo '$10,000' at the end. Hope I've explained it for you guys to understand easily enough, if not let me know. Thanks how do I echo "blah" after the first loop in a foreach loop and the in the rest of them echo "crazy"? I am working on a photo gallery script in which I need to show 9 images at a time. Here is my script so far Code: [Select] <?php foreach($pictures->result() as $p): ?> <?php for($i = 1; $i <= 9; $i++) { ?> <div class="item"> <ul> <li><a href="images/gallery/<?=$p->category;?>/<?=$p->photo_name;?>" rel="example1" ><img src="images/gallery/<?=$p->category;?>/thumb_<?=$p->photo_name;?>" alt="#" /></a></li> </ul> </div><!-- end item --> <?php } ?> <?php endforeach; ?> At the moment the script is showing one image at a time 9 times and for every entry in my database. I have been battling this for a little while now. Thanks in advance for all of your help! what im trying to do is echo all of the results from the database query but add bold to results with a pid of 0. here is my code: $list = ''; $query = $link->query("SELECT * FROM ".TBL_PREFIX."forums ORDER BY f_lid ASC"); $result = $query->fetchAll(); foreach($result as $key => $val) { if($result[$key]['f_pid'] == 0) { $list .= '<b>'.$result[$key]['f_name'].'</b><br />'; } $list .= $result[$key]['f_name'].'<br />'; } echo $list; this works fine but the ones with a pid of 0 are displayed twice. once as bold and then once normal like so: General General New Features Testing Testing Sandbox Bugs my question is how to prevent this. For some reason I'm getting an invalid argument supplied for foreach error and I'm not sure why. Code: [Select] <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['edit_event_lineup'])) { $event_items = $_POST['event_items']; $event_id = (int)$_POST['event_id']; foreach ($event_items as $items) { print_r($items); $segment_writer_id = (int)$_POST['segment_writer_id']; $introduction = mysqli_real_escape_string($dbc, $_POST['introduction']); $conclusion = mysqli_real_escape_string($dbc, $_POST['conclusion']); $segment_type = mysqli_real_escape_string($dbc, $_POST['segment_type']); $match_number = (int)$_POST['match_number']; $segment_number = (int)$_POST['segment_number']; $match_type_id = (int)$_POST['match_type_id']; $segment_title = mysqli_real_escape_string($dbc, $_POST['segment_title']); $match_type_id = mysqli_real_escape_string($dbc, $_POST['match_type_id']); $titles_id_list = mysqli_real_escape_string($dbc, $_POST['titles_id_list']); $stipulations_id_list = mysqli_real_escape_string($dbc, $_POST['stipulations_id_list']); $characters_id_list = mysqli_real_escape_string($dbc, $_POST['character_id_list']); $preview = mysqli_real_escape_string($dbc, $_POST['preview']); } $query = "INSERT INTO `event_segments` (event_id, segment_writer_id, segment_type, sort_order_preview, segment_title, preview, is_submitted_yes_or_no_id) VALUES ('".$event_id."', '".$match_writer_id."', '".$segment_type."' ,'".$sort_order_preview."','".$segment_title."','".$preview."',2)"; mysqli_query($dbc, $query); } ?> Does anybody know how to make the following code correct? real sorry but its just absolutely blowing my mind im awful with loops and have pretty much no clue what the hell im doing in honesty, any help would be great, Thanks Code: [Select] $addIDs_ary = array_map('intval', $_POST['chkInv']); $addIDs_ary = array_filter($addIDs_ary); $value = $addIDs_ary; //Check if hit_id is already in hitlist $query = mysql_query("SELECT * FROM hitlist WHERE player_id = '$playerID'"); $result = mysql_query($query); while ($result = mysql_fetch_assoc($result)) foreach ($result as $hit_id => $value){ if($result[$hit_id] == $value); $str = ""; } } else I have a foreach loop which shows the breadcrumb display. But it's stopped working. For some reason the links are no longer links. They are just echoed on screen with no <a> tags. setting up array: $crumb_query = mysqli_query($link, "SELECT f.forum_id, f.forum_cat_id, f.forum_name, c.cat_id, c.cat_name FROM ".TBL_PREFIX."forums as f LEFT JOIN ".TBL_PREFIX."categories as c ON c.cat_id = f.forum_cat_id WHERE f.forum_id = '$forum_id' ") or die(mysqli_error($link)); $crumb_info = mysqli_fetch_array($crumb_query, MYSQLI_ASSOC); $crumbs = array("index.php" => "Board Index", "./view_category.php?cid={$crumb_info['cat_id']}" => $crumb_info['cat_name'], "./view_topics.php?fid=$forum_id" => $crumb_info['forum_name']); echo build_crumbs($crumbs); the function: function build_crumbs($crumbs) { foreach($crumbs as $key => $value) { $crumb_display = "<a href=\"{$key}\">{$value}</a>"; $crumb_display = implode(" - ", $crumbs); } return $crumb_display; } can anyone see where im going wrong? hello. i have a foreach loop thats pulling out information that i dont want. how do i stop it. this is the loop Code: [Select] //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } the loop sits inside this function which has more loops Code: [Select] function listNavText($PHGlidA, $PHLobA, $PHLodA){ //GET THE LANGUAGE $langBS = basicSettings::find_by_id(1); $langID = $langBS->language_id; //GET THE LIST ORDER $PHLoa = PhLists::find_by_order($PHGlidA, $PHLobA, $PHLodA); foreach ($PHLoa as $PHLoas){ $PHLidA = $PHLoas->id; //GET THE LIST TEXT IDS $PCba = PCbridge::find_by_list($PHLidA, $langID); foreach ($PCba as $PCbas){ echo $PCidA = $PCbas->pageContent_id; //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } } } } this is what it echoes out 105L1-Title1 118 116 114 112 110 108L2-Title4 111 109L2-Title5 113 115 117 106L1-Title2 119 107L1-Title3 the number at the start is the text id L1-Title1 to L1-Title5 are tiles ($title) the spaces are links ($links) the problem is that i don't want the link spaces showing. just the 5 titles thanks I am using a foreach loop to get the results of an array. My problem is that I need the results combined into one string. How can I accomplish this? Hi everybody I am new to arrays, and loops pretty much, so please dont be mean! I am trying to turn a single upload form into a multiple upload form. My logic is I need to use arrays and loop the code for uploading the data from the form to the database (for each of these files, create a thumbnail, resize and rename original, move to folder, create path, and insert all that information into the db) But I have no idea how I've got this in the form (now) .... <pick an album to put the files into> <input type="file" name="image[]" > <input type="file" name="image[]" > and this is the code for the whole upload. It worked for single uploads ... but I'm now at a loss ... The code is abit messy, sorry. I'm fairly sure I need a foreach loop, but I dont know where to put it Really Really hoping you can help. Many thanks in advance Code: [Select] <?php ini_set("memory_limit","120M"); include ("DBCONNECT"); include ("CHECK ADMIN"); if ($admin != 1) { header("location:./login.php"); } else { define ("MAX_SIZE","5000"); define ("WIDTH","150"); define ("HEIGHT","100"); function make_thumb($img_name,$filename,$new_w,$new_h) { $ext=getExtension($img_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); $old_x=imageSX($src_img); $old_y=imageSY($src_img); $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); Imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); imagedestroy($dst_img); imagedestroy($src_img); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if(isset($_POST['submit1']) && !$errors) { $sqlalbum="INSERT INTO album (album_name) VALUES ('$_POST[newalbumname]')"; mysql_query($sqlalbum) or die ('Error, album_query failed : ' . mysql_error()); } If(isset($_POST['Submit'])) { $image=$_FILES['image']['name']; // if it is not empty if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension! You can only upload jpg, jpeg and png files</h1>'; $errors=1; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } $image_name=time().'.'.$extension; $newname="uploads/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { $thumb_name='uploads/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} If(isset($_POST['Submit']) && !$errors) { $album = $_POST['album']; $query = "INSERT INTO upload (name, path, album_id, thumbpath ) ". "VALUES ('$image_name', '$newname' , '$album', '$thumb_name')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } ?> $array = array("1","2","3"); foreach ($array as $value){ echo $value; } Put its only echoing out 3, not the whole array. Hi everyone, greetings from Brazil.
I am an average php coder, much more a designer than an programer, and i am in a looper trouble..
Can anyone try to help me?
Here is my code:
<table border="1"> <tr> <?php //pega cada uma das operadoras do campo operadoras $operadoras = $opers_trazOperadoras ; $logos = explode(",",$operadoras); $x = 0 ; foreach ($logos as $v) { mysql_select_db($database_webroker, $webroker); $query_trazLogoOperadora = "SELECT * FROM tb_operadora WHERE tb_operadora.id_operadora = " . $v ; $trazLogoOperadora = mysql_query($query_trazLogoOperadora, $webroker) or die(mysql_error()); $row_trazLogoOperadora = mysql_fetch_assoc($trazLogoOperadora); $totalRows_trazLogoOperadora = mysql_num_rows($trazLogoOperadora); ?> <td><img src="http://www.we-broker...imagens_upload/<?php echo $row_trazLogoOperadora['logo']; ?>"> <?php do { ?> <?php } while ($x++ < 4); { echo $x ;?> </td></tr><tr> <?php } $x = 0 ; } ?> </table> The URL for this code is: http://valsegs.we-br...radorasPATO.php Tks! Object- Take array of IP addresses and add up all occurrences of a particular IP address. //$item is an array of IP addresses foreach ($item as $key => $unique_ip) { if($unique_ip == $ip) $a++; } echo $a; I get a blank page. What am I missing? foreach ($export as $group => $arrayOpts) { //echo $arrayOpts[0]["choice"]; This returns No /** * If the option hasn't been selected, leave that part out entirely **/ if (!empty($arrayOpts)) // if the entire options array isn't empty, we'll display { if ($arrayOpts[0]["choice"]!="0" || $arrayOpts[0]["choice"]!="No") { $pdf->Cell(40,10,$group,0,1); $pdf->ImprovedTable($header,$arrayOpts); $pdf->Ln(); } } } Unfortunately I can't show print_r's at the moment, the main issue is it's running those $pdf-> lines even if that variable is equal to No, I proved it because up above commented out returns No, but it still runs the pdf code. Any thoughts? Been staring at it a while, maybe it's something in my conditional statement? Thanks. 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 Hello. I was wondering if anyone could please help with a problem I seem to be having a problem with my foreach loops. I have an array that holds other arrays. When I am trying to populate the database tables with the information in each array, things are going horribly wrong. This is my code: $tabledata = $this->db->get('tableinfo'); $i = 0; $_temp = array(); foreach($tabledata->result() as $row) { $data[$i] = $this->callAPI("lateststandings&records=3&category=" . $row->category . "&distance=" . $row->distance_id); array_push($_temp, $row->dbname); $i++; } $j = 0; foreach($data[$j]['Records']['Record'] as $record) { $record['FirstName'] .= " " . $record['LastName']; $this->db->replace($_temp[$j], $record); $j++; }
When this is run 2 things are happening:
1) What I am expecting to happen is, there should be 3 rows added to each table. But only 1 is being added to each table. I am not sure what I am doing wrong in these loops.
Hello to all I have problem a with my foreach loop.. First : Is it possible to rename each element that's been outputted everytime the loop execute? Code: [Select] <?php $arr = array(mikel, 17, cambodia, 50kgs, 5 feet, anna, 21, peru, 45kgs, 6 feet); foreach ($arr as &$value) { $value = $value; } ?> What i would like on the result of the foreach loop is name : mikel Age : 17 address : cambodia weight : 50kgs height : 5 feet is this possible? Second : i want to echo the result of the for each loop in every 5 turns. result 1 = mikel, 17, cambodia, 50kgs, 5 feet result 2 = anna, 21, peru, 45kgs, 6 feet Can anyone help me on this? thanks |