PHP - Issue With Foreach With If Statement
Hi I am new to PHP and I am having an issue with a foreach loop combined with an if statement, basically the if statement is getting the data from the first result in the foreach but not getting the second result, I have tried implement a count by using a variable to iterate but it isnt working: Code as follows: foreach(findCustomAlerts($customerid) as $key=>$value){ echo "ID of cat : ".$rifdid = $value['Catid']."<br>"; echo "Visits required per day : ".$visitsneeded= $value['Visits required']."<br>"; } foreach(getTodaysVisits($device_id) as $rfid){ foreach($rfid as $key=> $read){ if($key ==$rifdid && $read < $visitsneeded) { echo"<br>". $key." has not visited enough"; } } } Ouput is :
ID of cat : 5609 Array ( [rfid_id] => Array ( [23641] => 1 [5609] => 3 ) ). -------> this is the array data
----------------------------------------------- How can I get the loop to iterate to the next value?
Edited October 3, 2020 by Barand code block/indents Similar TutorialsHI, I have a foreach loop but after some execution it begins to show me this:Invalid argument supplied for foreach() ... so I want to exit from it.how can I do that? Thanks 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? I am having a go at writing my own simple gallery. As the I want to display an image from a folder in a directory of all the images... for example, I have 10 folders each containing images. I want my code to take image 01.jpg out of each folder and display it on my page, so that when I add folders to my main images folder, they will automatically be added to the page... but I only want the last 10 folders to display... so once I have 20 folders, it only shows 10. I also want the images to be 5 across and then make a new row. My folders will be numbered in order... 001, 002, 003, etc... and I need them sorted in reverse order, so the folder added last is displayed first. So... this is where I am at with the code : Code: [Select] $dir = "gallery/"; if (is_dir($dir)) { [color=red] foreach(array_keys($file) as $n) {[/color] if ($n+1 == 5) { echo "<td><img src=\"" . $dir . $file . "/01.jpg\" width=\"140px\" height=\"93px\" alt=\"\" /></td></tr><tr>"; } elseif ($n+1 > 10) { echo ""; } else { echo "<td><img src=\"" . $dir . $file . "/01.jpg\" width=\"140px\" height=\"93px\" alt=\"\" /></td>"; } closedir($dh); } } For some reason, I am getting the following error on the page : Warning: First argument to array_keys() should be an array in /path/to/gallery.php on line 8 Warning: Invalid argument supplied for foreach() in /path/to/gallery.php on line 8 line 8 is the one in red above. So... I have a couple of questions... 1. What have I done wrong so far? I cannot see it 2. How would I then go about putting the galleries in reverse order? I know it must be rsort, but not to sure if I need to do this first or after... ? Any help greatly appreciated, and I would also be greatful f an idiot's explanation, as I am really trying to understand all this! I'm getting there... slowly! I have some code that will update a record and is generic, meaning any POST variables can be used - whatever you have on the form. See below: Code: [Select] $set = array(); foreach($_POST as $field => $value){ $field = mysql_real_escape_string($field); $value = mysql_real_escape_string($value); $set[] = "`{$field}` = '{$value}'"; } $query .= implode(", ",$set) . " WHERE $id_name = '".$id."' LIMIT 1"; mysql_query($query) or die(mysql_error()); My question is, how would I modify this to insert a NEW record (not update an existing one). I'm not sure how to order this within a foreach statement because the add query has a different form: insert into tabel (all the fieldnames here) VALUES (all the values here) hi, i am having issues with sorting within a conditional statement. please see the code below. right now, i ve commented out the sorting below. basically i want to sort by: $venue1->hereNow->count. I am managing to pull the data correctly. see: http://marineboudeau.com/lab/4sq/ <?php if (is_object($venue->response)) { //sort($venue->response->groups[0]->items->hereNow->count); foreach ($venue->response->groups[0]->items as $venue1) { if ($venue1->hereNow->count != '0'){ //var_dump ($venue1); echo "<div style='font-weight:bold;'>".$venue1->name."</div>"; echo "<div>".$venue1->location->address." ".$venue1->location->city."</div>"; echo "<div>".$venue1->hereNow->count."</div>"; echo "</br>"; } } }?>() any idea what i need to do to make it happen? thank you. marine Hello I'm having problems regarding coding right the following problem One class (students) can have class all together or/and divided (haveDesdobramento) into 2 shifts So in the beginning i'm choosing all class and defined 100 hours Using a foreach because i need to check holidays, school breaks, start and end of school foreach (range( 0, $datediff ) as $day) { $internal_date = date( INTERNAL_FORMAT, strtotime( "{$startDate} + {$day} days" ) ); $this_day = date( INTERNAL_FORMAT, strtotime( $internal_date ) ); $this_month = date( INTERNAL_FORMAT, strtotime( $internal_date ) ); if($haveDesdobramento === "1") { if ((isSegunda( $internal_date )) && !isExcludedDate( $internal_date )) { $cronograma[$this_month][] = $this_day; if($temposSegunda != null) { if($sum>=$horasAll){ $nhoras = $sum - $horasAll; $temposSegunda = $temposSegunda - $nhoras; echo "tSegunda: ".$temposSegunda; } if ($haveDesdobramento === "1" && $haveAllClass === null) { if($totais<=$horasTurnos){ if ($sameDayShifts === "1") { $cronograma[$this_month][] = $temposSegunda; $cronograma[$this_month][] = $temposSegunda; } else{ $days = floor($horas/$temposSegunda); $hours_remaining = $horas - $days * $temposSegunda; $cronograma[$this_month][] = $hours_remaining; } } } if ($haveDesdobramento === "1" && $haveAllClass === "1") { if($sum<=$horasAll){ if ($sameDayShifts === "1") { $cronograma[$this_month][] = $temposSegunda; $cronograma[$this_month][] = $temposSegunda; } else { $cronograma[$this_month][] = $temposSegunda; $cronograma[$this_month][] = 0; $total += $temposSegunda; $cronograma[$this_month][] = $total; } } } else{ $days = floor($horas/$temposSegunda); $hours_remaining = $horas - $days * $temposSegunda; $cronograma[$this_month][] = $hours_remaining; } } $sum += $temposSegunda; } }
It works but it stops at 102, not 100 like it should (choosing 3 hours each time) and the array returned gives me this
Any help?
Thanks
2021-06-07 - 3 - 0 - 99 2021-06-14 - 3 - 0 - 102 Notice: Undefined offset: 1 in /home/esmaior/public_html/miga/db/crud/profissionais/response.php on line 661 2021-06-21 - - 0 - 102 Notice: Undefined offset: 1 in /home/esmaior/public_html/miga/db/crud/profissionais/response.php on line 670 Notice: Undefined offset: 1 in /home/esmaior/public_html/miga/db/crud/profissionais/response.php on line 661 2021-06-28 - - 0 - 102 Notice: Undefined offset: 1 in /home/esmaior/public_html/miga/db/crud/profissionais/response.php on line 670 Total: 102
hi phpfreaks In short I don't know what I am doing wrong. I have two arrays that preg_match_all then the results from that are placed into variables. The $valuematch is working fine but the $valuepath won't they print_r correctly but when I run the script and look at the source I find the option name shows nothing. Code: [Select] private function generateSelect ($menuString) { $return ='<select>'; preg_match_all('/href="(.*?)"/', $menuString, $path); print_r($path); preg_match_all('/title="(.*?)"/', $menuString, $matches); print_r($matches); foreach ($matches[1] as $key => $valueMatch) { $path[1] = $valuePath; $return .= "<option name='".$valuePath."'>".$valueMatch."</option>"; } $return.='</select>'; $this->selectOption =$return ; } I'm trying to figure out why its only showing the last child_links in the roster, events, and social objects. I've included the site that has the print_r of the array function. Any help would be appreciated. http://kansasoutlawwrestling.com/ Code: [Select] function getSubMenuPages() { $this->db->select('site_menu_structures.id'); $this->db->from('site_menu_structures'); $this->db->where('site_menu_structures.short_name', 'mainnav'); $query = $this->db->get(); $menu_id = $query->row()->id; $this->db->select('site_menu_structures_links.id, site_menu_structures_links.short_name, site_menu_structures_links.is_category'); $this->db->from('site_menu_structures_links'); $this->db->where('site_menu_structures_links.menu_structure_id', $menu_id); $query = $this->db->get(); if ($query->num_rows() > 0) { $linksArray = $query->result(); foreach ($linksArray as $key => $link) { if ($link->is_category == 'Yes') { $this->db->select('site_menu_structures_links_children.link_name, site_menu_structures_links_children.site_content_pages_id, site_menu_structures_links_children.link_url'); $this->db->from('site_menu_structures_links_children'); $this->db->where('site_menu_structures_links_children.site_menu_structures_links_id', $link->id); $query = $this->db->get(); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $site_content_page_id = $row->site_content_pages_id; $linksArray[$key]->child_links = array(); if ($site_content_page_id != 0) { $this->db->select('site_content_pages.content_page_name, site_content_pages.permalink'); $this->db->from('site_content_pages'); $this->db->where('site_content_pages.id', $site_content_page_id); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $linksArray[$key]->child_links = array( 'link_name' => $row->content_page_name, 'link_url' => $row->permalink ); } } else { $linksArray[$key]->child_links = array( 'link_name' => $row->link_name, 'link_url' => $row->link_url ); } } } } } } return $linksArray; } This kind of has me in lala land as this is very strange... I'm going through a list of dates in such format. Code: [Select] [earned] => Array ( [0] => 2010-07-14T11:26:09Z [1] => 2010-07-31T06:35:14Z [2] => 2010-07-14T11:25:55Z [3] => 2010-07-31T06:29:43Z [4] => 2010-07-31T06:31:47Z [5] => 2010-07-14T11:26:17Z ) Everything is setup correctly but the first offset of an array comes back blank. Like so. - 2010-07-14T11:26:09Z 1280558114 - 2010-07-31T06:35:14Z 1279106755 - 2010-07-14T11:25:55Z 1280557783 - 2010-07-31T06:29:43Z 1280557907 - 2010-07-31T06:31:47Z 1279106777 - 2010-07-14T11:26:17Z Now if I manually use strtotime on just 2010-07-14T11:26:09Z I get the value I seek (1279106769) My foreach setup... Code: [Select] foreach($trophy['earned'] as $key2=>$value2) { echo strtotime($trophy['earned'][$key2]) . " - " . $trophy['earned'][$key2] . "<br />"; } Any ideas? Hey there folks, Im trying to get a foreach loop working correctly from a json source epg heres my code: https://pastebin.com/FjHj1EF6 Here is the current output, which.. while correct is only the first instance of these values i wanted using the foreach loop, i would love any tips on why my approach failed and to be pointed in the right direction. While it has to be included: $url = "https://mywebsite.fake/mlb.php?id={$arr['games'][0]["gamePk"]}"; this value isn't related to the assistance im asking for. that will work for my purposes later. but for now i just need to understand the issue with the foreach loop. Thanks in advance for your thoughtful response. mosb3rgler 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? After deciding to venture into the realm of prepared statements, I have this line in my script Quoteif ($stmt = $conn->prepare('SELECT username FROM users WHERE username = ?')) { Everything was working fine. I reviewed my code to adjust it to my old habits, and realized that I had hardcoded the TABLE NAME rather than using a variable. I updated my code to Quote$table = "users"; if ($stmt = $conn->prepare('SELECT username FROM $table WHERE username = ?')) { and results from my SELECT statement vanished. Is the use of a variable for a table's name outdated? Even possible?? This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm having issues with the following: Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['password']=$_POST['password']; if($_SESSION['username']=="username" && $_SESSION['password']=="password"){ if($_GET['product']=="add"){ $content.=' <p><label>Product Name:</label> <input type="text" name="product_name" size="30" /> <label>Product Price:</label> <input type="text" name="product_price" size="5" /> </p> <p><label>Product Category:</label> <input type="text" name="product_category" size="30" /></p> <p><label>Product Link:</label> <input type="text" name="product_link" size="30" /></p> <p><label>Product Image:</label> <input type="text" name="product_image" size="30" /></p> <p><label>Product Tag:</label> <input type="text" name="product_tag" size="30" /></p> <p><label>Product Keywords:</label> <input type="text" name="keyword" size="30" /></p> <p><label>Product Features:</label><br /> <textarea name="product_features" rows="10" cols="60"></textarea> </p> <p><label>Product Pros:</label><br /> <textarea name="product_pros" rows="5" cols="30"></textarea> </p> <p><label>Product Cons:</label><br /> <textarea name="product_cons" rows="5" cols="30"></textarea> </p> <p><label>Product Description:</label><br /> <textarea name="product_description" rows="10" cols="60"></textarea> </p> <p><label>Product Notes:</label><br /> <textarea name="product_notes" rows="5" cols="30"></textarea> </p> '; $logout='<div><a href="./acp_admincp.php?log-out">Log-Out</a></div>'; } elseif($_GET['product']=="view"){ } else{ $content.=' <a href="./admincp.php?product=add">Add New Product</a> <br /> <a href="./admincp.php?product=view">View Products</a> '; } } elseif(isset($_GET['log-out'])){ session_start(); session_unset(); session_destroy(); header("Location: ./admincp.php"); } else{ $content=' <form action="./admincp.php" method="post"> <p><label>Username:</label> <input type="text" name="username" size="30" />'; $content.='</p> <p><label>Password:</label> <input type="password" name="password" /></p>'; $content.='<p><input type="submit" value="Submit" name="Submit" /></p> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <base href="http://ghosthuntersportal.com/" /> <title>Ghost Hunter's Portal - Admin Control Panel</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="verify-v1" content="" /> <meta name="keywords" content="ghost, hunters, hunter, ghosts, spirit, spirits, paranormal, investigation, investigator, investigators, k2, emf, meter, kii" /> <meta name="description" content="Ghost Hunters Potal. Parnormal research equipment store." /> <meta name="author" content="Andrew McCarrick" /> <meta name="robots" content="index, follow" <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <img src="./logo.png" alt="Ghost Hunter's Portal Admin Control Panel" /> <br /> <div style="color: #AA44AA; font-size: 26px; margin-top: -30px; margin-left: 125px;">Admin Control Panel</div> <?php echo $logout; echo $content; ?> </body> </html> I can log-in, and get to the page with the two links on it. However, once I click one of the links it falls back to the log-in page, and it ends up being a never ending loop. It's doing this: Log-In --> Page with links ---> Log-In page again Should be doing this: Log-In --> Page with links --> Add Product page or View Products page I can never get into the the actual sub page. Just to be clear, the address bar actually shows product=add or product=view, but it still shows the log-in page. 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, "; } } Hello Everyone, I have to change the if statements to a switch statement, in this game. Can anyone help? Thanks. var checkKeyPressed = function (e) { // Press key A or key D to make dog run to the left or right // The running speed is specified by the step variable, 10 by default. // If you replace 10 with a larger integer, the dog will run faster. //press A, dog runs left if (e.keyCode == "65") { if (prex[0] > 5) { prex[0] = prex[0] - step; } } //press D, dog runs right if (e.keyCode == "68") { if (prex[0] < right) { prex[0] = prex[0] + step; } } }; Hi All, I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each property that is associated with the search: <ul> <?php foreach($properties as $property) { ?> <li><?=$property->$zipcode?></li> <?php } ?> </ul> How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code? Thanks in advance! P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors. Anyways, thanks in advance for the help! I am trying to develop a calendar. I have code to determine the number of days for each month. I want to cycle through each day and spit out code for each day. Something like the following: Code: [Select] <?php $month = "December"; $days = 31; foreach($days){ echo "<div id='day_block'> ".$days." </div>"; } ?> i think i need to use a counter but don't know how, any help would be awesome! i have a table that echos 10 entries what i want to do is once it echos 5 records it starts a new table. I dont know how to go about this. Could you guys guide me the right way. today i programmed my own weight calculator. one thing i am having a problem is with trying to make it so if a weight is over a certain number, then the shipping price will increase by X. shipping prices are charged in 20000 gram blocks, so if I have something that is 22000 grams then that will be two blocks. what i need to do is something like (this is a big guess) Quote $row3 = 50; $weighttotal = 22000; if ($weighttotal > 20000) { foreach (20000) { $row3 += $row3;} } } } can it be done on php?? |