PHP - Appending A String In A Foreach Loop
Hello.
I'm trying to append the loop keys and values into a string and store it into a hidden field. This is the code I have : Code: [Select] if (isset($_POST['ordered'])) { // We can assign $_POST['product'] to a variable to make it easier to type out $prod = $_POST['product']; // Throw a little intro to see how many they checked echo 'You selected ' , count($_POST['ordered']) , ' products.'; // Now we loop through it and get the IDS that were selected // Foreach lets you select the $key and the $value for each iteration of the loop // $strOrder = ""; foreach ($_POST['ordered'] as $key=>$id) { echo '<p/> ProdName: ' , $prod[$id]['name'] , '<br/> ProdPrice: ' , $prod[$id]['price'] , '<br/> ProdQty: ' , $prod[$id]['qty'] , ' <hr/>'; $strOrder .= $key . " " . $id; $TOT += $prod[$id]['price'] * $prod[$id]['qty']; } $TOT2 = $TOT + 55; echo '<input type="hidden" Name="TOT" value ="'. $TOT .'">'; echo '<input type="hidden" name="TOT2" value =". $TOT2 .'">'; echo '<input type="hidden" name="Order" value=". $strOrder . '">'; } strOrder does not get set to a value. Similar TutorialsHello dear community, good day! first of all: Merry Christmas to all of you!! How to combine / concatenate a *divided* string in order to use this combined / concatenated string in a loop where i run the $dom = new DOMDocument(); @$dom->loadHTMLFile('<- path to the file-> =60119'); and the following.... numbers - Note: they replace the ending!!! 60299 64643 62958 63678 60419 60585 60749 60962 and so on. ( Question: How to combine the string (in fact the string is an URL) so that i am able to build the URLs automatically. And that i am able to run all that in a loop - eg with foreach [probably this is the right way to do that]. I hope that i was able to explain the question so that you understand it. If i have to be more descriptive - just let me know! Many many thanks for a hint! db1 Hi I have an array of items that I am currently displaying a foreach loop What I'm looking to do, is add a string, to all of items, a part from the last 4: foreach ($pager->getResults() as $items => $item) { echo $item->getName(); //need to add a string to this for the all but the last 4 } Thanks Hello, i have the code below and i need to have all results in a variable as a string, inside the loop they are displayed how i want but outside will echo the last result. Thank You. Code: [Select] foreach($_POST as $key=>$value){ if (is_numeric($value)) { $valoare = "$value,"; } } echo $valoare; 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. I have an array of $fl By using values of this array, i want to create a new string. I need string size will be maximum 200 characters. When i try below code snipped, $f value is added to string two times. How can i add $f to array only one time, with checking size of string. Thank you Code: [Select] $fl=getsomelist(); // gives an array $userList=''; foreach ($fl as $f) { if ( strlen($userList .= $f) <= (200) ) { $userList .= $f; } else { break; } } Hey guys This is the first loop i have attempted on my own, so please tell me if ive done something completely stupid.. What happens is the suer specifies a number of thumbnails on the previous page, these are posted to the form and then that amount of thumbnails should be displayed. Heres what i have so far $cd = 0; while ($cd < $numberofthumbnails) { $displaythumbs . '<div class="ThumbnailHolder"> <div class="LeftThumb"><a class="group" href="../../../Images/Lighthouses/Beachy-Head/1.png"><img src="../../../Images/Lighthouses/Beachy-Head/Mini/Thumbnail-1.png" width="430" height="200" alt="Thumbnail 1"></a></div> <div class="RightThumb"><a class="group" href="../../../Images/Lighthouses/Beachy-Head/2.png"><img src="../../../Images/Lighthouses/Beachy-Head/Mini/Thumbnail-2.png" width="430" height="200" alt="Thumbnail 2"></a></div></div> '; $cd++; } Essentially what im trying to do is as thumbnail code to $displaythumbs for each time the loop goes round. What am i doing wrong? Thanks Danny. 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 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); } ?> 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? 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. 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! how do I echo "blah" after the first loop in a foreach loop and the in the rest of them echo "crazy"? 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 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 guess I'll rephrase since my wording wasn't very clear. Why don't echo "<p>\n"; if (!empty($locations) && is_array($locations)) { foreach ($locations as $field => $val) { if ($field == "City") { echo $field . ' : ' . $val . "<br />\n"; $val = $cityvar; } if ($field == "ZipPostalCode") { echo $field . ' : ' . $val . "<br />\n"; $val = $zipvar; } if ($field == "CountryName") { echo $field . ' : ' . $val . "<br />\n"; $val = $countryvar; } } } echo "</p>\n"; hello why does my div move when i use a foreach loop ? if i use the code below i get the following i added a border style to the div so i can see that some are in and some are out: result 1 = not in a div result 2 = in a div result 3 = in a div etc then on the end i get a div with no result in it Code: [Select] function name(){ echo' <div id="divName">'; $a = Class::find_all(); foreach ($a as $ab){ $name = $ab->name; $dest = $ab->destination; <ul> <li><a href="index.php?pageID='.$dest.'">'.$name.'</a></li> </ul>'; } echo'</div>'; } thanks rick 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! 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. Hiya! I have an issue, here is my code. <?php class generateInvoice { private $invoiceID; public function __construct($invoiceID) { $this->_INID = mysql_real_escape_string($invoiceID); } public function __drawInvoice() { $get_invoice = "SELECT * FROM `invoices` WHERE `id` = '$this->_INID' LIMIT 1"; $run_get_invoice = mysql_query($get_invoice); if($run_get_invoice) { if(mysql_num_rows($run_get_invoice) == 1) { while($invoice_m = mysql_fetch_assoc($run_get_invoice)) { if($invoice_m == 1) { $status = 'Awaiting Payment'; } elseif($invoice_m == 2) { $status = 'Paid'; } $items_mass = explode(',', $invoice_m['items']); foreach($items_mass as $item_key => $item_value) { $item_split = explode('-', $item_value); echo '<pre>' . print_r($item_split, true) . '</pre>'; foreach($item_split as $item_key_final => $item_value_final) { $invoice .= ' <tr class="item-row"> <td class="item-name"><div class="delete-wpr">' . $item_value_final[1] . '</div></td> <td class="description">THIS IS THE DESCRIPTION</td> <td><span class="cost">$650.00</span></td> <td><span class="qty">1</span></td> <td><span class="price">$650.00</span></td> </tr>'; } } } return $invoice; } else { return false; } } else { return false; } } } ?> This is what is displayed. Array ( => 1 [1] => Test Product [2] => 6.99 [3] => 2 ) Array ( => 5 [1] => Tester Product [2] => 600.99 [3] => 1 ) THIS IS THE DESCRIPTION $650.00 1 $650.00 e THIS IS THE DESCRIPTION $650.00 1 $650.00 . THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 e THIS IS THE DESCRIPTION $650.00 1 $650.00 0 THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 I need it so that I can use each of the array's above and echo out each item (key) individually. I don't understand whats going wrong? Many thanks, James. |