PHP - Using Explode To Fill An Array
I have a form that saves the input data as such:
Quote bass inshore offshore Array, regional, mid, 70, 40, 2 x yr, all, fellowship knowledge information learnig, one, one, three, four, one, one, two, three, three, four, TPWD round table discussions conservation biology, the guide talking about fishing the venturi, Jack Ellis and TAG fishing in the East Texas creeks., none at present bass inshore offshore Array, regional, mid, 70, 40, 2 x yr, all, fellowship knowledge information learnig, one, one, three, four, one, one, two, three, three, four, TPWD round table discussions conservation biology, the guide talking about fishing the venturi, Jack Ellis and TAG fishing in the East Texas creeks., none at present bass inshore offshore Array, regional, mid, 70, 40, 2 x yr, all, fellowship knowledge information learnig, one, one, three, four, one, one, two, three, three, four, TPWD round table discussions conservation biology, the guide talking about fishing the venturi, Jack Ellis and TAG fishing in the East Texas creeks., none at present This php program reads it back to the screen as it is writen and as you see it above. Code: [Select] <?php $YourFile = "meeting.survey"; $handle = fopen($YourFile, 'r'); while (!feof($handle)) { $Data = fgets($handle); print $Data; print "<hr>"; } fclose($handle); ?> The code below fails. I feel it is because I am using 'explode' incorrectly. Code: [Select] <?php $YourFile = "meeting.survey"; $handle = fopen($YourFile, 'r'); while (!feof($handle)) { $Data = fgets($handle); $answers = explode(',', $Data); print $answers[0]; print $answers[1]; print $answers[2]; print $answers[3]; print $answers[4]; print $answers[5]; print $answers[6]; print $answers[7]; print $answers[8]; print $answers[9]; print $answers[10]; print $answers[11]; print $answers[12]; print $answers[13]; print $answers[14]; print $answers[15]; print $answers[16]; print $answers[17]; print $answers[18]; print $answers[19]; print $answers[20]; print $answers[21]; print "<hr>"; } fclose($handle); ?> My PHP coding skills are minimal at best, any help, direction, comments you have will be greatly appreciated. If you wish to view the survey html go here If you wish to view the php code used to produce the data, Code: [Select] wget http://texasflyfishers.org/quiz/php_tutorial/survey.php If you wish to view a readback of the data go here Everything I've been able to find over the web, tells me this is what I need to do if I want to add some text that tells what each responce means. Similar TutorialsHi, I'm trying to explode an array into a multidimensional array using <br /> tags as splitters but just can't get the syntax right! I can do lines of the array one by one, but not the whole lot at once. I'd really appreciate a quick example of an explode inside an array. $myarray looks something like this with print_r: ( [0] => [1] => some_html<br />some_html<br />some_html<br /> [2] => some_html<br />some_html<br />some_html<br /> [3] => some_html<br />some_html<br />some_html<br /> ) and I want to turn it into this: ( [0] => [1] => [0]some_html [1]some_html [2]some_html [2] => [0]some_html [1]some_html [2]some_html [3] => [0]some_html [1]some_html [2]some_html ) I've tried this $myarray = explode ("<br />", $myarray); but it doesn't work … It doesn't matter too much if there's are a few empty lines in the array from the final <br /> tags. Many thanks, as ever, for any help. Hi all! This is probably fairly simple for someone who is used to dealing with arrays. I have an array of data(Parsed from an XML document) containing a string I would like to further split into another array. The string is along the lines of: "<name>":<value>,"ID":20251,"ID2":2300,"ID3":2000 How can I split the above into: Array[<NAME>] => <VALUE> Notes: <name> changes often. depending on the query, it may have different <name> values. I have been trying to do it with preg_split and got to: Array ( => "<NAME>":<VALUE> [1] => "ID":20251) but I need to split it further at ":". I tried a foreach, but I failed miserably. Can anyone point me in the direction of better practice for arrays/preg_split? I have looked into the PHP documentation, but it is not enough for me. Thanks in advance I have in ONE MySQL database row a string of ID's like this: Name of Row: Values: Post IDs 10 14 52 37 And now I want to fetch those ID's explode them (by the space) and then use them as an array, like this: $array[] = explode(" ", $query); echo $array[0]; // 10 echo $array[1]; // 14 echo $array[2]; // 52 Is this possible, if yes how can I do this? I have strings that can look like this "monkeys / cats/ dogs / snakes". I have code that breaks the items apart and puts each as a separate item into an array, like this (where $getstring['thestring'] equals strings like the example given above)... Code: [Select] $array = explode("/", strtolower(trim($getstring['thestring']))); foreach($array as $k=>$v) { $array[$k] = trim($v); } } My question is how can I add some code so that if there are ever instances where there is nothing between each /, it does NOT put that "blank" into the array? For example, if a string was something like "monkeys / cats/ / dogs/ eagles / / snakes", the code now would create two array items that are essentially "blank" because there were two consecutive slashes, two different times in that same string. These strings are entered by users so there is definitely a possibility they make a mistake such as above so I need a way to weed out those mistakes (i.e. the blanks). Any ideas for easiest way to find the "blanks" and NOT have them in the array? Hey, Im trying make a way to check an input to make sure it only consists of "1,2,3,4,5,6,7,8,9,0 and . " I thought i could explode the number and check it to an array that has "1,2,3,4,5,6,7,8,9,0 and . " I havent worked with arrays before so i dont quite know how they work or to go about this? Any ideas cause im sure im not the first to ask for something like this Thanks hey guys, I apologize, as this stuff should be easy to figure out, but I am getting stumped again being a php rookie. I have searched a lot for an answer before I bothered you all. Here's the skinny: I have a string coming in via post content that looks like: name1\x1ddata1\x1ename2\x1ddata2\x1e ... where the delimiters are 0x1e for the field/data pairs and 0x1d between the field/data . there may be as many as 20 of these pairs in the string. I have the string and I can store the pairs with explode in an array correctly, I just cant seem to get them all into one array. it would be even more helpful if the first element of the pairs were the array keys. Any guidance would be helpful. Thanks Code: [Select] $raw_post_data=file_get_contents("php://input"); $records=explode("\x1e",$raw_post_data,-1); foreach($records as $data){ $pairs=explode("\x1d",$data);} Ok, this was driving me nuts. I think I found the cause, but need help fixing it. I have a bunch of answers in a MySQL database in the form of... Miami Heat/heat/miami Orlando Magic / orlando/ magic etc. etc. *Notice how sometimes there are leading or ending spaces (i.e there is a space before "magic" but NOT a space before "miami")... I run this code to bring back the answers data (all acceptable answers) in an array. I then look for the user entered answer ($userinput, which has trim and strtolower run on it) in the array. Using this code below, the answer IS found if $userinput is any of the Miami Heat options, but it is NOT found if it's any of the Orlando Magic options. The only difference is the fact that there are spaces in the Orlando Magic stuff. Apparently, the trim() function is only removing space from the beggining and end of the ENTIRE string. But I need to trim() each item in the array. How can I do this? Seems like it should be easy but can't figure it out. Code: [Select] $sql = "SELECT * FROM answers WHERE quizid = $quizid"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($getanswers = mysql_fetch_array($result)) { $array = explode("/", strtolower(trim($getanswers['answer']))); if (in_array($userinput,$array)) { echo "the answerid = " . $getanswers['answerid'] . "<br>"; } else { echo "the answerid is not found= <br>"; } } } Hi there, Need a little help here if anyone has the time. In short, I have a page that is dynamic, that sends POST data to a handler, pretty standard stuff. Normally, for me anyway, I know what the field names will be in advance and handle then as usual. In this case the form content is created dynamically from a GUI I created and the names of the fields are suffixed with the product ID. Within the handler I have stripped the POST data down to the main two vars, namely the pid- product ID and qty- quantity ordered and within a loop created a string to explode() like; 9_33_21_66 $oStrArray = explode('_', $ostring); echo "ostring[0] =".$oStrArray[0]; echo "ostring[1] =".$oStrArray[1]; echo "ostring[2] =".$oStrArray[2]; echo "ostring[3] =".$oStrArray[3]; Result => ostring[0] =9 ostring[1] =33 ostring[2] =21 ostring[3] =66 Now, the 1st, 3rd, 5th etc will be the pid and the 2nd, 4th, 6th etc. will be the qty. Only two sets are used in this example, normally 50+ pairs of values will be present. If it helps with the loop that I need to create - if a foreach will not suffice - I can deduce how may pairs will be present and send this as a var via GET from the form setting a value for i, for instance. I need to be able to, within a loop, * pull the first value as a pid * run a subroutine to pull the data from the DB table to get all the product info to display on a confirmation page [this is not ecom - just emailed orders for existing clients] I can do all the MySQL Query stuff it is just rationalising the data extracted from the array Well I am sure you can see from that what I am trying to do, I will need to do the multiplications etc. I do not know how to handle the data in the array created by the explode() In logic I would say this if x in $ostring is even then $ostring is a product id [mysql query to get details from table] next item in array is corresponding quantity - print details of product in a table, do the multiplication to give line total and add to $message ready for email - NEXT pair of vars I really hope that makes sense and someone can point me in the right direction - thanks in advance for any assistance. Regards A Hi, I'm not sure if this is a wierd one, I have lots of arrays i'm looping through like this to see them:- for($i=0; $i <count($confirmed); $i++){//loop through print_r_html($confirmed[$i]); } Which shows the following :- Code: [Select] Array ( [0] => AAAAAA-BBBBBB [1] => 2 [2] => 2010-09-29 ) Array ( [0] => AAAAAA-BBBBBB [1] => 2 [2] => 2010-09-28 ) Array ( [0] => CCCCCC-DDDDDD-EEEEEE [1] => 3 [2] => 2010-09-29 ) Key 0 is a Groupconcat split by "-" Key 1 shows how many fields are in 0 Key 2 is just the date What I would like to do is split the first array into 2 arrays, the second in 2, and the third into 3 (therefore ungrouping the groupconcat if you will) as such:- Code: [Select] First into these two:- Array ( [0] => AAAAAA [1] => 2 [2] => 2010-09-29 ) Array ( [0] => BBBBBB [1] => 2 [2] => 2010-09-29 ) Second into these two:- Array ( [0] => AAAAAA [1] => 2 [2] => 2010-09-28 ) Array ( [0] => BBBBBB [1] => 2 [2] => 2010-09-28 ) Third into these two:- Array ( [0] => CCCCCC [1] => 3 [2] => 2010-09-29 ) Array ( [0] => DDDDDD [1] => 3 [2] => 2010-09-29 ) Array ( [0] => EEEEEE [1] => 3 [2] => 2010-09-29 ) ) I know I can get out the info from the first of the keys in each array by putting this into the loop:- for($i=0; $i <count($confirmed); $i++){//loop through if($i==0){ $seperated[] = explode("-",$confirmed[$i]);//split by "-" } } print_r_html($seperated); but i'm not sure how to copy the other keys at the same time? If anyone has got any ideas that would be great! thanks in advance Kev. I am working on a csv file import to mysql, which will include items in one table (irrelevant here), and a hierarchical table of categories (id | name | parent). I would think the simplest method to get each category name is too explode the categories from the csv into an array, for example: $array = "root/Business/Employment"; $categories = explode("/", $array); My problem though, is figuring out what the ID's are for each of the categories without knowing each name will be unique and not knowing for sure the full depth of each category hierarchy either. So (I think) I need to rely on the category structure to define the lowest level ID. So something like this: Code: [Select] SELECT t1.parent AS p1, t1.name AS lev1, t1.id AS cat1, t2.name AS lev2, t2.id AS cat2 FROM (categories AS t1) LEFT JOIN categories AS t2 ON t2.parent = t1.id WHERE t1.parent = '1' AND t2.name = "Employment"; This gives me the ID of Employment, but it's easily possible that the name will be duplicated somewhere else in another heirarchy (in fact I get 4 results from phpmyadmin). And since I don't know all these will be only 3 levels deep, it won't work all the time. Any ideas help would be greatly appeciated! Hi, I am a little bit new to php, and I am learning about array functions. I just wanted to know the difference between implode and explode in arrays, and how each of them would be used? Thank you! Hello everyone I'm very new here but i hope you could help me with a tricky problem I no longer know how to approach it because it's difficult to visalize the solution. Anyway, I have a script that goes to the root of a site (with cURL) and picks up categories (links on the site) via regex. All the links are placed into the big array I have. The first layer (dimension) I've managed to create but the problem comes to when I need my script to delve into deeper dimensions. I want, for each link it finds, go to that page and find those subcategories and place it in my array in the correct subarray. If the regex returns 0 matches, go up one step and go to the next node's site, until the whole big array has been exhausted. Is this possible? Please help out guys and gals. I'll provide more info and code if requested. If I explode a string well using a substring when I implode that substring is now missing. for example. Code: [Select] $exploded = explode("[MAC]",$data); $data = implode($exploded); Now [MAC] would be missing in the $data string. any way to get around this? Hi, In my mysql database i have a text input option, in the registration form and edit my details form i have a multiple select dropdown list, which user selects options to populate the text input box, which ultimately populates the text field in the mysql database. All works perfectly. The dropdownlist consists of 3 parts <optgroups> first is current selection (what is the usesr current selection)works fine, The second <optgroup> is existing words, what words we(the site) have given as options, and the third <optgroup> is the words that others have used. This is where im having a small problem. Because its a text field when i call the data from the database, it calls the entire text box as a single option in my select list.. I want to break the words in the text field (at the comma) and have them listed each one as an option in the select list. Example what i need: Words in text box:(my input allows the "comma") word1, word2, word3, word4, word5, word6, How i want them called/displayed: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> here's my code: $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $original_functionsexperience =doSelectSql($query,1); $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $functionsexperiencelist=doSelectSql($query); $funcexpList ="<select multiple=\"multiple\" onchange=\"setFunctionsexperience(this.options)\">"; foreach ($functionsexperiencelist as $functionsexperienceal) { $selected=""; if ($functionsexperienceals->allwords == $original_functionsexperience) $selected=' selected="selected"'; $allwords=$functionsexperienceal->allwords; $funcexpList .= "<optgroup label=\"Current selection\"> <option value=\"".$allwords."\" ".$selected." >".$allwords."</option> </optgroup> <optgroup label=\"Existing Words\"> <option value=\"existing1,\">existing1</option> <option value=\"existing2,\">existing2</option> <option value=\"existing3,\">existing3</option> <option value=\"existing4,\">existing4</option> <option value=\"existing5,\">existing5</option> <option value=\"existing6,\">existing6</option> </optgroup> <optgroup label=\"Others added\"> //heres problem <option value=\"".$allwordsgeneral."\">".$allwordsgeneral."</option> </optgroup>"; } $funcexpList.="</select>"; $output['FUNCEXPLIST']=$funcexpList; The result im getting for optgroup others added: word1, word2, word3, word4, word5, how can i get it like this: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> i want to explode a text field on the fly ? for example city,region.country and to turn it to city_id,region_id,country_id 1.textfield from autocomplete 2.get post variable 3.explode 4 get ids i played around with some ajax with php Code: [Select] <html> <body> <input name="searchField" id="searchField" type="text" value="<?php echo $_POST['searchField'];?>"/> <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari }catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("No AJAX!?"); return false; } } } xmlHttp.onreadystatechange=function(){ document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText; var t=setTimeout('Ajax()',1000); clearTimeout(t); } var searchfieldvalue=encodeURIComponent(document.getElementById("searchField").value) xmlHttp.open("GET","getid.php?searchField="+searchFieldvalue+"",true); xmlHttp.send(null); } window.onload=function(){ var t= setTimeout('Ajax()',1000); } </script> <?php /*explode searchField and generate ids $searchField=$_POST['searchField']; $p = explode(" , ", $searchField, 3); $cityname=mysql_real_escape_string($p['0']); $regionname=mysql_real_escape_string($p['1']); $countryname=mysql_real_escape_string($p['2']); */ ?> <div id="ReloadThis">Default text</div> </body> </html> //getid <?php $p=array(); $p = explode(" , ", $_GET['searchField'], 3); echo $cityname=$p['0']; echo $regionname=$p['1']; echo $countryname=$p['2']; echo'<input type="hidden" name="place" id="place" value="'.$cityname.'"/> <input type="hidden" name="region" id="region" value="'.$regionname.'"/> <input type="hidden" name="country" id="country" value="'.$countryname.'"/>'; here ill add function to get city_id() etc ?> Hi, I have an array for prices : forfait="158|Group Session,95|Group half session,45|Private Course,90|zumba course" which is used in a dropdown list where it shows as Group Session (158$) Group half session (95$) etc... The prices need to be used as an 'amount' field on the gift certificate as the descriptions must show as a 'label' on the gift certificate. So, I need to ' explode ' both the prices and the descriptions separately. I can 'explode' de prices using $tmp_forfait=explode("|", $value) and I get 158 95 45 and 90 But, how do I get the descriptions separately, without the prices meaning I need to 'explode' the digits and '|' ... Anyone can help me with that cope please? Thank you Hello Ive got a text area and i want to seperate each link that is placed inside the text area,. Is there a way using php exlode or somthing to reconise that the link has finished? Each of the links in the text area are on a new line. Thanks in advance. Hi all, I posted a similar question before and got some of the way but still need a little help. I have a product database with a description column where there are strings broken into lines. I need to find a way to explode() by line break. Currently explode("/n") doesn't work - it only returns one array item. Can anyone help me out? Thanks! Lets say I have a URL of http://mydomain.com/somename/ I need a function to grab USERNAME However I need it to work if someone uses http://www.mydomain.com/USERNAME/ OR With or without the trailing / after USERNAME I can't see to figure anything out which accounts for the many different variables that a person could type it. And yet another way is that the URL could be http://www.mydomain.com/USERNAME/SOME-CAT/SOME-POST/ Thanks |