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] . '''
}
}
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
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.
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:
Using Array_intersect() Without Keeyping Keys From The Array1, I.e. Re-number Intersect Array Keys.
I only use indexed arrays. When I use array_intersect function, of $a3 = array_intersect( $a1, $a2 ), I just need the vales of intersect array and let keys to be re-numberred from 0.; I found the intersect array $a3 have the correct values but keep the keys of $a1. When I use for loop from $index=0 to sizeof ($a3)-1, by $a3[$index], php reports "undefined offset " problem. How can I re-number the keys of $a3 from 0 to sizeof($a3)-1;
Foreach Is Returning Value Of First Key For All Keys
I'm having trouble with the foreach function. I'm using it twice inside a user defined function with two different arrays, and in the second instance it's returning the value of the first key for all the keys. My code is shown below and the problem areas are marked with comments. In case you're wondering, this script is for generating sticky checkboxes that include an event handler. <form> <?php if (! is_array($like)) { $like = array(); } function make_checkbox_click ($name, $query, $options, $onClick) { foreach ($options as $value => $label) { printf('<label><input type="checkbox" name="%s[]" value="%s" ', $name, $value); # This is the instance of foreach that's not working correctly. # It's returning the value of the first key for all the keys. foreach ($onClick as $key => $event) { printf ('onClick="%s" ', $event); } if (in_array($value, $query)) { echo "checked "; } echo "/> $label</label><br /> "; } } # End of user defined function. $characteristics = array( 'personality' => ' I love their personalities.', 'minds' => ' I admire their minds.', ); # This is the array that foreach isn't working correctly with. $charClick = array ( 'personality' => "alert('Aren't they the greatest?');", 'minds' => "alert('They're smarter than most people their age.');", ); make_checkbox_click (posPoints, $posPoints, $characteristics, $charClick); ?> </form>
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>"; }
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.
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?
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:
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?
Using Max() On Array Keys
i am using an array to store contact data within a session. it looks like this: $_SESSION['contact'][$key][<content>] $key counts the set of records, so i have $_SESSION['contact'][Ɔ'] $_SESSION['contact'][Ƈ'] $_SESSION['contact'][ƈ'] and so forth. [<content>] stands for the fields containing the actual set of data, which are stored within the [$key]-arrays. at one point i need to find out what the highest value of $key is. running max($_SESSION['contact']) simply leaves me with "Array()" as the result. what i am doing wrong, and how do i correct it?
Array Keys
is it possible to use only a key in an array meaning: $arr["a"]="yo"; $arr["bc"]="ygo"; $arr["eea"]="wgyo"; $arr["fa"]; $arr["a"]="yo"; and then somehow get all the keys without and value i tried: while (list ($key) = each ($arr)) {print $key;} but i doens't seem to work.
Array Keys
If I used a "for each" to go through an array or irregularly numbed keys, is there a way to get the key number that the loop is currently on each time?
Array Keys
Been trying to figure out an array issue. For some reason when I echo $key it's echoing "Array". I want it to return the key (in this case adventure). Code:
Automatic Array Keys
My array keys are behaving strangely. In the manual it says calling an array like $array[] = "something" should make the value be put into the next available integer key available. However, my values are being placed with whole sets of blank keys inbetween. Here's what part of the print_r() of the array returns: Code:
Print Out Array Keys Only
Hi, there are lots of examples that show you how to print array values given a key. Do you know how to print keys for a given array. example $myArray = array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4); How do you print 'a', 'b', 'c','d' only without using any loops?
Printing Out Array Keys
i'm trying to find a simple way of printing out the keys in an array generated by mysql_fetch_array which returns a single row. i.e. while ($row=mysql_fetch_array($result) ) { print out the $row keys and values } is this possible?
Write Array Keys To SQL
I have an array of data. I want to write each key in the array to its own row in SQL. what would be the best way to accomplish this?
Prepend Array Keys With A String
I have looked on uk.php.net for the function I need but can't find it. Does anyone know what the function is called who's purpose is: to recurse through an array and assign values to keys whilst prepending the key name with a string specified by one of the function parameters?
Getting Deep Array Value Without Knowing Keys?
I've racked my brain for the last few hours trying to figure this one out. I have an array of language strings such as : $lang = array(); $lang['en']['prompt']['hello'] = 'hello' $lang['en']['prompt']['bye'] = 'goodbye' $lang['en']['number']['first'] = Ƈst' This is being used by an ajax routine, so I don't know which string will be requested at runtime. So, I've got $lang and a request ('en_prompt_hello'), and tried a few things such as: $request = explode ($request); $found_string = array_intersect_assoc ($lang, $request); to no avail. Short of having to do a complicated recursion searching at every available depth, is there an easy way to do this?
Multibyte Strings As Array Keys
Does this work? Something is breaking when I try to do this, and all I can think of is that PHP does not allow multibyte array keys.
Sort An Array Using 2nd Dimension Keys
I need to sort an array (configured as shown) based on one of the second dimension keys. [1] ['File_Name'] => test.doc; [1] ['File_Type'] => MS Word; [1]['Size'] => 50; [2]['File_Name'] => test.pdf; [2]['File_Type'] => Adobe PDF [2]['Size'] => 150 [3]['File_Name'] => test.xls; [4]['File_Type'] => MS Excel; [5]['Size'] => 60; For example, I'd like the order of the 1st dimension keys (integer indices) to reflect the order if the array is sorted by the "File_Type" key.
Argument To Keys() Should Be An Array In Main.inc On Line 152
I am getting the following errors: Warning: Argument to keys() should be an array in main.inc on line 152 Warning: Non array argument supplied for foreach() in main.inc on line 152 I've developed the site on my linux box at home using PHP 4.0.3pl1. It works great, but when I upload it to my hosting service I get the above messages. I've tried all the different ways to go through an associative array. I've tried doing an implode(array_keys($arr), ',') then split on ','. It keeps coming back to the fact that it doesn't recognize the array I declare right before it is an array. The hosting service runs a BSD Bosx and uses PHP 4.0b2. I'm wondering if this was a problem with the second beta release or if it is something screwy between platforms. Why does it work great on my box but when I upload it it craps out?
Getting Keys/values From POST Array In An Orderly Fashion..
I've got this javascript that results in the following being posted; weight_1 = 30 cost_1 = 20 amount_1 = 32 weight_3 = 65 cost_3 = 23 amount_3 = 12 weight_7 = 43 cost_7 = 9 amount_7 = 12 etc.., with the numbers appended to the keys (here 1, 3, and 7) ascending but not sequential. I need my PHP recieving these POST keys/values to present them like this: #1 Weight: 30 Cost: 20 Amount: 30 #2 Weight: 65 Cost: 23 Amount: 12 #1 Weight: 43 Cost: 9 Amount: 12 Whats' the right way to do this? I've been messing around with array functions but haven't quite figured out which to use..
Foreach - Array
i want to modify an array in foreach loop foreach($array as $ele){ $ele = $some_random_string; } i should see here the modified $array .
Foreach On Checkbox Array
I am having a bit of an issue getting a foreach statement i have made to work , essentially what this for each statement is suposed to do is write a row to a database for each one of the check boxes selected here is the code:
MySQL Array/foreach
I have table with about 20 fields in it. I want to be able to dynamically pull the data for a certain record and create an array with the keys as the fields names and of course the data as the value. Here's what I have so far (and it's not working ): function get_data($record_id) { $query = mysql_query("SELECT * FROM table where record_id = '$record_id'") or die(mysql_error()); while($row = mysql_fetch_array($query )) { foreach ($row as $key => $value) { $data .= "&$key=$value"; } } return $data; } Now I want to be able to call the function and work with the data I'm trying to call. $record_id = 'xxxxxxxxx'; $test = get_data($record_id); $name = $test['username']; //This would be the username field from the table echo $name; All I get is a blank screen when I run this and I know the problem is in the foreach statement I tried to write.
Foreach On A Long Array
My array: $pos_array = array( 0 => array("p1_pts" => $pts_1, "user_id" => "$p1_id", "pos" => 0), 1 => array("p2_pts" => $pts_2, "user_id" => "$p2_id", "pos" => 1), 2 => array("p3_pts" => $pts_3, "user_id" => "$p3_id", "pos" => 2)); How would I do a Foreach on a long array like this? I know the basic ($pos_array as $x => $y) but not anything bigger.
2 Dimensional Array And Foreach
I have a 2-dimensional array. so I run it through two foreach loops to get the data out. but, i want the foreaches to run in reverse. lets say I have an array[3,2]. right now my foreach prints [1,1] [1,2] new line [2,1][2,2] new line [3,1][3,2] and i want it to print [1,1][2,1][3,1] new line [1,2][2,2][3,2]
Foreach() Multidimensional Array
I did a search for other foreach() problems and cant seem to find a solution that fits my syntax, probably because I'm a newbie. Here is my code:
Unique Array Values In Foreach
I have a snippet of code below. In my foreach, I would like to process only 1 item per hdd value, in the case below, the echo $tib['hdd'] . " "; would only display 1 and 2, not 1,1,1,1,2,2,2,2. It doesn't matter which one shows, because I only want the unique value for hdd. $tibs = array( "tib1" => array("drive" => "C", "progress" => "on", "hdd" => "1", "partition" => "1", "compression" => "3", "backup" => "K:"), "tib2" => array("drive" => "D", "progress" => "on", "hdd" => "1", "partition" => "2", "compression" => "3", "backup" => "K:"), "tib3" => array("drive" => "E", "progress" => "on", "hdd" => "1", "partition" => "3", "compression" => "3", "backup" => "K:"), "tib4" => array("drive" => "F", "progress" => "on", "hdd" => "1", "partition" => "4", "compression" => "3", "backup" => "K:"), "tib5" => array("drive" => "G", "progress" => "on", "hdd" => "2", "partition" => "1", "compression" => "3", "backup" => "L:"), "tib6" => array("drive" => "H", "progress" => "on", "hdd" => "2", "partition" => "2", "compression" => "3", "backup" => "L:"), "tib7" => array("drive" => "I", "progress" => "on", "hdd" => "2", "partition" => "3", "compression" => "3", "backup" => "L:"), "tib8" => array("drive" => "J", "progress" => "on", "hdd" => "2", "partition" => "4", "compression" => "3", "backup" => "L:"), ); foreach($tibs as $tib) { echo $tib['hdd'] . " "; }
Modify An Array Inside A Foreach
I am using a foreach statement to read an array. But at some point, I want to change the value of the array, but it doesn't work. My code is: if ($aProvisions) foreach($aProvisions as $iKey => $aProvision){ if ($aProvision['cod']==0) $aProvision['cod']= 3; } I have tried to fix it regarding some comments found on google: if ($aProvisions) foreach($aProvisions as $iKey => $aProvision){ if ($aProvision['cod']==0) $aProvisions[$iKey]['cod']= 3; } But it still isn't working. I finally tried to make the modification OUTSIDE the foreach: if ($aProvisions) foreach($aProvisions as $iKey => $aProvision){ $aInsertions = array(); if ($aProvision['cod']==0){ $aInsertion = array(); $aInsertion[] = $iKey; $aInsertion[] = 3; $aInsertions[] = $aInsertion; } } if ($aInsertions) foreach($aInsertions as $aInsertion){ $iPos = $aInsertion[0]; $aProvisions[$iPos]['cod'] = $aInsertion[1]; } I can't modify it in any way?
Safe To Delete Elements Of Array In Foreach
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to
Accessing Numerical Array Index In Foreach
I have no trouble looping through an array using foreach. To keep track of the index, I set a variable before the loop and increment it in the loop: $index = 0; foreach ($array as $item) { blah; $index++; do something that requires knowing the index of the current item; } Is there a better way to access that index value?
Array Print Problem With Foreach Statment
I have an php script with, what I think is a small array problem....this is a piece of the code. Basically the loop gets data from a form then does an insert of the array into my database, which all woks except for the last field ....part_status... foreach($_POST["part"] as $key=>$val) { $qty = $_POST["qty"][$key]; $part_status = $_POST["part_status"][$key]; $data_insert.='("'.$val.'", "'.$qty.'", "'.$part_status.'"),'; echo "Part Number: $val QTY: $qty Part Status: $part_status<br /> "; } //remove last comma $data_insert=substr($data_insert,0,-1); $sql_parts="INSERT INTO tbl_service_calls_parts (part_number,qty, part_status) VALUES ".$data_insert.""; this is the result: ....What the hell is that "0" about.... it should say "Part Status" just like the line before it. Part Number: FF3-001-000 QTY: 2 Part Status: Part Used Part Number: AA2-001-000 QTY: 5 Part Status: 0 I'm at a loss, if I drop the "$part_status = $_POST["part_status"][$key];" the script works fine.
While Loop From Array
I have an array, let's call it $namesarray which is full of names. How do I create a loop such as a while loop to repeat for every value (name) in the array?
Array And Loop
I am making progress but still not coming up with the right solution. I have a horizontal nav bar that has drop down navigation - the drop down navigation is populated from my database based on the user the list will be different. Meaning I have 1 table that stores the navigation links (called sanavbars) and another that stores the users (called sauser) and then a 3rd table that stores which links from sanavbars each user has access to. Now I want to change the class of the horizontal nav bar which contains the current page (e.g. basename($_SERVER['SCRIPT_NAME'])) in one of its sub navigation links.
Multidimensional Array Loop
I am trying to loop through a multidimensional array shopping cart stored in a session. I can loop through it ok but the problem is that when the page displays I have two each of the items in the cart. I am looping through with a double foreach. If I do print "$key: $value"; inside of the second foreach I get the correct display of the items in my cart but then the actual display of the items gives me two of each. Code:
Using A Loop To Create An Array
I am trying to populate an array with information found in a mysql database. By selecting a state they would then see every resort that contains the selected state in it's row... Kind of like a tree navigation system. Code:
Loop To Enter An Array Into A Db
Can I use a loop to enter an array into a db and still have it in the same row as the rest of the data and still be useable? I don't want to serialize it.
|