Foreach Loop With Nested Arrays
I haven't programmed in PHP in quite a while. Could anyone help me
with a foreach loop in a nested array? I have a function which returns
$stock (for an online pricing catalog).
$stock[0] is ( [0] =Item, [1] =Sale, ...) an array of column
headers.
$stock[1][$i] is ([Item] =SL, [Sale] =300, ...) an array of
column headers to value for item $i
What I have to print the header row for the pricing table is:
print("<TR>");
foreach ($stock[0] as $num =$val) {
print("<TH>" + $val + "</TH>");
}
print("</TR>");
I've also tried ($stock[0] as $x) print($x).
What returns is five zeroes. Not in table cells, just "<TR>00000</
TR>".
Does anyone have any ideas what I've done?
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Nested Foreach Loop
I am using this code for to udpate a database that holds stats for my hockey league. This particular section updates the penalty minutes for a given players. I get these values by inputting them into a form and then using a script that updates the database. The penalty section is the difficult one for me because I in one textarea I input the players jersey number and then in onother textarea I input the corresponding penalty minutes for that player. So I get the values from the form and then convert it them to arrays with the explode function. Code:
Foreach Loop Contains Arrays In Some Values
I'm looping through the keys and values of a form submission using foreach($_POST as $key => $value) echo "$key = $value<br>"; No problems there. All works as expected. But seveal of the values are arrays and the echo comes out like: subjectone = Array subjecttwo = Array There could be as many as 9 elements in each array but there may be as few as one. How can I get those $value that are arrays to echo the entire array using a foreach loop? I would like to end up with all values printed in the page whether in an array or not.
Nested Foreach
foreach($test as $var1){ foreach($test2 as $var2) { echo '"var1: " . $var1[1] . "<br>"var2: " . $var2[1] . "<br> "' } } -------------------- The $tests have values just that this nested loop doesnt work i keep getting this error message Warning: Invalid argument supplied for foreach() What is the correct way to nest a foreach
Nested ForEach?
Is it possible to nest a foreach loop inside another? If so is this done properly then: Code:
Dynamic Recursive/nested Foreach (part Deux) With Filtering
I originally wanted to figure a method to better implement a nested foreach to calculate all the permutations held within an array. After posting the topic and getting great responses an elegant solution was found. I then increased the difficulty by requesting that we also include a method to "filter" or "skip" certain values during permutation calculation. The original solution finder quickly came back with yet another code snippet listed below which acomplished the request...it was mere childs play it seems for them (sasa). I marked the topic solved as the original question had been solved. I am creating this new thread as I am once again adding an additional layer of difficulty. The final previous solution is listed first as a reference, followed by the new and more complex problem underneath that one. My attempts to shunt in the functionality have all failed I think due to the recursive nature...any takers? Code:
Nested Loop
foreach($test as $var1){ foreach($test2 as $var2) { echo '"var1: " . $var1[1] . "<br>"var2: " . $var2[1] . "<br> "' } } -------------------- The $tests have values just that this nested loop doesnt work i keep getting this error message Warning: Invalid argument supplied for foreach()
Nested Arrays
I have a nested array: Array ( [AiHist_SelectResult] => Array ( [clsASCAiHist] => Array ( [0] => Array ( [HistID] => 0 [AiID] => 0 [TimestampUTC] => Array ( [IsNull] => false [Value] => 632851929000000000 ) [AiValue] => 17.2 ) I only want to print the AiValue How can i do that?
Nested Arrays In 4.4.4 Vs. 4.3.11
On PHP Version 4.4.4 (my development machine) the following code works great. But when I place this on my host which is running 4.3.11, it does not work. Note on line 11, I create an array that is passed into another array on line 22. This seems to be the issue. On 4.4.4 these values passed in on line 22 are remembered. When I run it on 4.3.11, the arguments passed in are forgotten. See bad result. The places where you see "default" should be player names that where set on line 22. Code:
Nested While Loop Isn't Working
while ($row = mysql_fetch_object($result)) { while ( $row1 = mysql_fetch_object($result1)) { printf("<tr><td>$row->stationip</td><td>$row1->stationip</td></tr>");}} My problem is.. the first while loop only loops through one time and the second loop, loops all the way through like it should, and the loops exit.
Nested Loop, 2 MySQL Tables
I have a set of nested links, and at one time each category one had all the same subcategories. Now that has changed - each category has different subcategories. I have a tree menu, but now it just shows all subs under each category, of course. I have 2 tables - one for categories, one for subcategories - they are related by the categoryID. I think I have the SQL fine (have tried several different versions - see most recent/uncluttered below), but how do I get it to work correctly in the tree loop? SELECT DISTINCT cat.catName, cat.catDesc, subcat.subcatName FROM cat, subcat WHERE cat.catID = subcat.catID; Tree example: cat.catName(1) subcat.subcatName(1) subcat.subcatName(2) cat.catName(2) subcat.subcatName(3) subcat.subcatName(4)
Variable Losing Set Value In Loop/nested If()
just having some trouble with the variables $agility and $eagility losing their set initial values (in this case 5 and 8 respectively) when in the following code: $agility = $ag1; $eagility = $ag2; while ($hitpoints >= 1 and $ehitpoints >= 1) { if ($agility >= $eagility) { $ehitpoints = $ehitpoints - $strength; echo $ehitpoints . " you <br>"; $eagility = $eagility + $ag2; } else { $hitpoints = $hitpoints - $estrength; echo $hitpoints . " enemy <br>"; $agility = $agility + $ag1; }} the $ag1 and $ag2 variables seem to have the same problem, however $hitpoints, $ehitpoints and $estrength seem to be holding the correct values.
Arrays And Foreach
I have a multi-dimensionsal array in the form of a 6 x 10 table. I have 2 problems: 1) The foreach statement that inputs each row into a table, and 2) The php syntax in the table. First, I'm still building, so the input is in the form of a string that I 'extract' data from. There are 7 input strings in the following form: Code:
Using Str_replace In Foreach Loop
I'm trying to set up a php script to handle input from a form. One thing I want to do is to replace any semicolons that were entered with commas. I have str_replace working to do it like so: $question1 = str_replace(";", ",", $question1); $question2 = str_replace(";", ",", $question2); And it works. But since I have a lot of fields, I thought it would be more efficient to parse them with a foreach loop. But that's where I'm having a problem. I tried this but it doesn't work: foreach ($_POST as $k=>$v) { $_POST[$k] = str_replace('', ',', $v); $_POST[$k] = $v; } Can anyone show me what I need to do to get this foreach loop working properly?
Limit And Foreach Loop
like you can limit results with for and while loops but how do i display , say 9 out of 15 results. when i have to use foreach loop?
Why Does Foreach Display Each Loop Twice
//this loop doesnt work as intended, each row displays twice, once with a number as $key and again with key name as $key!? Any ideas why? $result = mysql_query("SELECT * FROM tbl WHERE id = Ƈ' "); while($row = mysql_fetch_array($result)) { foreach ($row as $key =$value) { echo "<tr><td style='width:150px'>$key</td><td>$value</td></tr>"; }
Looping Through Arrays With Foreach
Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement For example: <?php $arr = array("one", "two", "three"); foreach ($arr as $value) { echo "Value: $value "; } ?> This will output: Value: one Value: two Value: three --=[ Why not to use list & each ]=-- Another method to loop through an array is the following: <?php while (list(, $value) = each($arr)) { echo "Value: $value<br /> "; } ?> This has some disadvantages: - It is less clear, because list() looks like a function but actually works the other way around: instead of returning something, it takes a parameter by being the left-hand side of the expression and assigns values to the parameters. - You have to reset() the array if you want to loop through it again. - It is approx. three times slower than foreach. --=[ About for & count ]=-- Another method to loop through an array: for ($i = 0; $i < count($arr); $i++) { echo "value: $arr[$i] "; } Consider this array: array(5 => "Five"); The above for-loop would loop from elements 0 through 5, while only one element exists. If this is what you want, the for-loop is an effective way to loop through an array. If not, use foreach instead.
Foreach Loop With Array Keys
I am unable to get the following piece of code to work as desired. The fields valuable seems to contain all values however the vaules variable only contains the first assignied with $values = ''' . $arry[$keys[0]] . ''' $keys = array_keys($arry); $fields = '`' . $keys[0] . '`' $values = ''' . $arry[$keys[0]] . ''' foreach($keys as $key) { if($key != $keys[0]) { $fields .= ', `' . $key . '`' $vaules .= ', '' . $arry[$key] . ''' } }
Variables Inside A Foreach Loop
I have two arrays that have Spring and Fall specific dates. They do exactly what I want but, when I put them on the same page, the first array, Spring months, prints out then the second array, Fall months, prints out and then the first array prints out again. Its not supposed to do that at all. However, I dont see what is causing the second printing of the first array. Here are the two arrays.....
Strange Results From Foreach Loop
I'm attemting to create dynamic buttons based on the count of questions in a database. The button has 3 states, blank, selected, and inactive. The script below works great, but with a strange bug that seems impossible to me. When the $question_count and $question_id are 2 or more values apart the script works, but when they are only 1 value apart, it bugs out. Examples... -- $question_count = "5"; $question_id = "2"; Output: q1.gif q2_selected.gif q3.gif q4.gif q5.gif -- $question_count = "4"; $question_id = "2"; Output: q1.gif q2_selected.gif q3.gif q4.gif q5_blank.gif -- $question_count = "4"; $question_id = "4"; Output: q1.gif q2.gif q3.gif q4_selected.gif q5_blank.gif -- $question_count = "4"; $question_id = "3"; Output: q1.gif q2.gif q3_selected.gif q4_selected.gif <--- WTF q5_blank.gif
Foreach Loop Stops After First Pass
I'm trying to make a script upload several images at once. I have a form which creates an array of files, with title and description for each file. The following script is supposed to handle the files properly, one by one, but it stops after the first image. I've tried with different images, different filetypes and so on, and I am basically stuck. What am I missing? Code:
Position In Array In A Foreach Loop
I have a script that checks an array for names and if that person's name is there it will e-mail them a particular variable. Here is the setup: an array such as $names = array( $name1, $name2, $name3, $name4 ); etc. Then a foreach loop foreach ( $names as $person ){ if ( $key == 1 ){ $color = blue;}} However I need something that will get the position in the array of the variable that the foreach loop is dealing with. I tried array_search but that gets screwed up if someone is in the array more than once, it will then only stop at the first time they are in the away.
Foreach Loop With Logical Operator?
Can I use AND or && in a foreach loop, like this: foreach ($_POST['day'] as $day && $_POST['event'] as $event) { $query = "INSERT INTO event(year,day,event) VALUES('$_POST[year]','$day','$event')"; } Or is there some other way to do this?
Printing Arrays In A ForEach Statement?
I have the the following script which simply parses a remote file and sets the item I am looking for into an array. My question is how do I turn that array into an echo or print statement. PHP Code:
Accessing Multiple Arrays Using Foreach
I have been searching all afternoon for an answer to this and haven´t found a solution so my last resort is asking here I am collecting links from a few documents on our site using this: <?php $data = file_get_contents('http://www.example.com/'); preg_match_all("/out.php?url=(.+?)" target/",$data,$match); preg_match_all("/class="id" title="(.+?)"/",$data,$desc); foreach($match[1] as $url ) && foreach($desc[1] as $fulldesc){ echo urldecode($url); echo "| $fulldesc<br>"; }?> Basically , I want to output all the links and their respective descriptions separated by a pipe character. But reading from the two arrays is giving me a bit of a hard time.I now know I cannot use the && operator, I just left it in so you guys could see what I´m trying to do. How can I do this? I´m not much of a programmer but from what I have read the other option I have is using multi-dimensional arrays? I might be extracting the URL, the description and then some more data later on so this might be a better approach.
Adding Values To An Array In A Foreach Loop.
I am creating a function for my horse site that will choose the color of the horse. I have a database full of horse breeds and all the possible colors they can be. Here is what the "color" column might hold for one of the horse breeds: solid,paint The word "solid" can be a bunch of different colors...so I am trying to make my script add all these colors to an array I am populating that holds all the possible colors for that breed. Here is my current code for the function with comments to let you know what is going on Code:
For Loop And Arrays
I'm trying to create a function to execute multiple backups at once, using the following code:
For Loop And Arrays
I'm trying to run through an array which has each value in element 1-3. For example: for($x=1;$x<3;$x++){ echo "$array[$x]" } Is this not valid code, because it doesn't seem to work. Also, is there another way to do this?
Comparing 2 Arrays In A Loop
I have 2 arrays: $array1[] = 'hello'; $array1[] = 'how'; $array1[] = 'are'; $array1[] = 'you'; $array1[] = 'bob'; $array2[] = 'hello how'; $array2[] = 'are you steve'; I want to compare $array1 with $array2, and if any value of $array1 is found in $array2 I want to perform an action I know this has to be in a loop, i'm confused about how to set it up.
Help With Str_replace & $_FILES Arrays Need To Loop?
Ok I am trying to get these loops figured out I have 10 files being uploaded- $_FILES['pic1-10'] I need to run str_replace on all 10 to eliminate any oddities " ","%20" to clean up the filenames before inserting names in db. foreach ($_FILES as $n) { $name=$n["name"] str_replace( " ", "",$name) now how do I get it read back into $_FILES['pic1']['name'] and continure on to pic2?
Creating Table Rows For Ever Other Loop In A WHILE Loop
I'm trying to create a table using a MySQL fetch array while loop that would look like this: CONTENT1 CONTENT2 CONTENT3 CONTENT4 CONTENT5 CONTENT6 I need a <TR></TR> for every other piece of content. But I don't know how to do this with a loop that uses a MySQL fetch array while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { PHP CODE THAT IS LOOPED;}; I'm trying to remember from my old college Java class that we did something with loops for whenever the counter variable was even the loop would do something special... I don't know if this is possible with a while+mysql_fetch_array loop though.
Nested SSI And PHP Woes
I am trying to use a nested SSI (SSI with a call to another SSI inside it) on my index page, but my index page is a .php file. I think the problem I am running into is that the second SSI is not being parsed due to the page being a php page. Any suggestions? By the way, the nested SSI file works fine on the other .html pages. We have added SSI to the apache server as a parsable extension, and that is what made the nested SSI's work on the html pages, but it still will not work on the php pages like our index.php page.
Nested Functions...
I've inherited some code, which is not working as it is supposed to. The way it's implemented has me confused. It looks something like this:
Possible Nested If Problem?
Within this chunk of code is a primary if statement, followed by two nested if statements, and then concluded with an else to compliment the initial if statement. My problem is that when I attempt to assign a value to a variable $someText before the two nested if statements, then it is not assigned properly. Everything in this bit looks opened and closed properly to me. Is there a problem with this code? PHP Code:
Nested Classes In PHP?
I remember reading that both nested classes and namespaces would be available in PHP5. I know that namespaces got canceled (much sadness...), however, I *thought* that nested classes were still an option. However, I am coming up dry looking for information on how to do this, and the most recent references I am able to find to nested classes in PHP are dated 2003. And they all say the same thing: sorry, can't do that. So, it's not possible? Is that the end of the matter? Any suggestions for attempting to implement namespaces in PHP5? Some sort of hack or workaround?
Nested Query
I need the second query to display its results based on the 'townid' from the first query. I am not sure how to pass it. The page variable is '$countyid'. As you can see I have used a 'townid' of '11' as an example if I dont make any sense. Code:
Nested SQL Query
I'm currently working on a project for a database class I'm taking. It's a simple database that displays movie showtimes and such. My problem is that when I try to nest a query inside the "while" of another query I only end up with one result. Here is the code, is what I'm trying possible? Code:
Nested IF's
I am trying to create a basic registration script for my University project. Problem is nested if's are giving me a headache, i will post the code, the idea is you first enter your details your details and they get validated on register.php. If somone knows how to get register.php?step=1,2 then that would be a better idea. Code:
Creating A For Loop Inside Another For Loop.
I'm trying to write a script that will display questions that are in one flat file and answers from another flat file. In addition, there are copies of these files with their own data in multiple folders. I created a for loop to work with an array of the different file paths to the different folders. Then I created a for loop inside of that one to display the questions and answers files that is in each folder. All I get when I run the script is the first folder and it's questions and then it stops there. PHP Code:
Nested Select Statements
I have used nested select statements in ORACLE before but it seems to be trouble some. I want to split my results of a query into pages on a web page. Yes it is easy using LIMIT but the problem is that when you sort/order you results the LIMIT doesn't apply to the new order. I have tried a nested select statement but it wouldn't work. MySQL respond with a syntax error message. For example SELECT VARIABLE1 FROM (SELECT VARIABLE1 FROM TABLE1 ORDER BY VARIABLE2) LIMIT 0, 10 Hope someone can help me.....
Cannot Get Nested For/while To Work Properly
I feel like this should be extremely simple, but I cannot for the life of me get it to cooperate. Part of one of my functions pulls data out of a database and build an array, but the index variable doesn't seem to be available within the while loop. for($i = 0; $i < $numAlts; $i++) { while($row = $db->sql_fetchrow($result)) { echo $i; $tempArray[($row['name'].$i)] = array('name' => $row['name'].$i, 'value' => $row['value'], 'show' => $row['show'], 'required' => $row['required']); } array_push($array, $tempArray); } the echo was put in there to help me debug the thing. It should be echoing 123... but instead it echo's 00000000. The nested loops work fine, exiting when they should, but every row has the same name eg Name0. Is there some weird PHP variable scoping that I'm not aware of?
Regex Nested Backreferences
For my web-based php regex find/replace do-hickey, I need to match individual back references and wrap a tag around them so they'll be unique to the rest of the match for individual color markup. Initially this would seem easy enough, however not all of a potential regex match is going to be within a back reference. So it's necessary to replace the back reference, and only the back reference, while preserving the context of the match. For example, if I were to search the text fish this fish fish looking for ..*?(?<=this )(fish).* I'd match everything, capturing the second instance of fish into the back reference. I can't simply take the match and run a replace for fish in order to apply the highlighting, because then i'd end up with 3 highlighted "fish", 2 of which weren't supposed to be. I also couldn't simply return the back reference with the markup, as that wouldn't return the non-back referenced stuff. My initial solution was to run the original find text over the match to get the back references, using an extra flag to have it return the offset of each back reference. So now I have the location of the text within the string, and can get the length of it from that point from the string itself. Going backwards so as not to mess with the numeric location with in the string, it captures back references without losing context or data. Perfect. .. . . until back references are nested. In this example: (.*?(?<=this )(fish).*) back reference 1 would be fish this fish fish, back reference 2 would be fish -- here's where the problem surfaces. If I wrap back reference 2 in the markup, when I apply back reference 1's markup it's going to apply the end tag in the wrong place since the string has increased and the original length calculated no longer applies. If I replace back reference 1 first, same problem. I'm sure there's some obvious, simple solution I'm overlooking having exhausted a bunch of complex attempts to compensate for it. Any fresh perspectives on the best way to markup nested groups while preserving the integrity of the return? Below is the function the matches are being passed through, you'll see I'm useing preg_match_all to get the capture groups as well as the match location and then using substr_repalce to insert the pseudo-markup. function hltr($text,$find) { preg_match_all($find,$text,$hlight,PREG_OFFSET_CAP TURE+PREG_SET_ORDER); if ( isset($_POST['debug']) || isset($_GET['debug']) ) { echo "<pre>"; print_r($hlight); echo "</pre>"; } $n=count($hlight[0])-1; $text = $hlight[0][0][0]; while ( $n > 0 ) { $text = substr_replace($text,"back$n::".$hlight[0][$n][0]."::bk",$hlight[0][$n][1],strlen($hlight[0][$n][0])); $n--; } return('<strong class="result">'.$text.'</strong>');
Problem With Nested If-else Statement
I'm setting up an auction website using PHP and MySQL. There in the section where logged in members can put up new auction in a form, I want to run a form validation where I used if else statements to check the fileds filled. In the form page there are two radio buttons - fixed and auction - (only one can be chosen) and depend upon which one is chosen some text should be inserted in the text fields. For that I'm using a validation where this nested if else is not working properly. It checks until some if statements then won't check the rest of the if statements. The codes below I have reduced to relevant parts. names of radio buttons: groupname - 'rdoAuctionType', with 'fixed', 'auction' text fields: when 'fixed' button is selected, text field 'txtFixedPrice' must be filled when 'auction' button is selected, text fields 'txtStartPrice' and 'txtIncrement' must be filled ---------------------------------------------------------------------------*------------------------------------------------------------ Here is the code: auction_formvalidation.php if(isset($_POST['btnConfirm'])) { ............. ............. $auctiontype = $_POST['rdoAuctionType']; $fixedprice = $_POST['txtFixedPrice']; $startprice = $_POST['txtStartPrice']; $bidincrement = $_POST['txtIncrement']; $duration = $_POST['txtDuration']; ........... if { ..... } else if { ...... } else if(trim($auctiontype) != '') { if(trim($auctiontype) == 'fixed') { if(trim($fixedprice) == '') { $errmsg .= '<li>Please enter the fixed price.</li>' } else if(!isNumber($fixedprice)){ $errmsg .= '<li>Fixed price should only contain numbers.</ li>' } } else if(trim($auctiontype) == 'auction'){ if(trim($startprice) == '') { $errmsg .= '<li>Please enter the start price.</li>' } else if(!isNumber($startprice)) { $errmsg .= '<li>Start price should only contain numbers.</ li>' } else if(trim($bidincrement) == '') { $errmsg .= '<li>Please enter your bid increment.</li>' } else if(!isNumber($bidincrement)) { $errmsg .= '<li>Bid increment should only contain numbers.</ li>' } } } else if(trim($duration) == '') { <----------------- it doent check from here ownwards $errmsg .= '<li>Please enter the duration for the auction.</li>' } else if { ....... } } Code of form page: add_auction.php <html> .............. .............. <form name="formRegister" action="add_auction.php" method="post"> <fieldset> ............... ............... ............... <label>Auction Type:</label> <table border="0"> <tr> <td valign="top"><input type="radio" name="rdoAuctionType" value="fixed" <?if ($auctiontype == 'fixed') echo "checked";? Quote:
How To Execute Nested PHP Scripts
I've got a PHP script that browse a database and extracts from it parts of HTML code. Some of these parts contain other PHP scripts In my webpage i've got a first PHP script similar to this one: PHP Code:
|