PHP - Explode And Foreach Problems.
$st = $rowcompany['states']; $statesearch = explode(',', $st); $st has already been declared via mysql query earlier in the document. What I am trying to accomplish here is when a user profile is listed as say "New York, Ohio" or however many states they wish to have on their profile, it will explode the states list that is seperated by commas. Then it should search the mysql database for each state it breaks out via explode. With this code it is stopping at New York and not showing Ohio results in the select list options. <?php foreach($statesearch as $s){ echo "You Searched $s "; } echo "<form action='phpforms/updatecounties.php' method='POST'>"; echo "<select name='counties[]' MULTIPLE SIZE=5>"; foreach($statesearch as $s){ //Connect to the database include_once 'phpforms/connect.php'; $sql = mysql_query("SELECT * FROM counties WHERE state LIKE '$s'"); while($row = mysql_fetch_array($sql)){ $counties = $row['counties']; echo "<option value='$counties'>$counties</option>"; }//End While }//End Foreach echo "</select>"; echo "<input type='submit' name='button' value='Update The Counties You Cover'>"; echo "</form>"; ?> Similar TutorialsIf 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, I have two problems with reading a XML file with SimpleXML and the foreach loop: Problem number one: If I have an item with only one "segment" child, I get the error "Fatal error: Call to a member function attributes() on a non-object in /var/www/readxml.php on line 28". My way of using a $segnum variable which I increment is maybe not necessary since it is a foreach loop... But what would be the right way? Problem number two: My code only sums up the size of the first two segments, but it should sum up all. What's the problem here? My xml file for testing looks like this: Code: [Select] <?xml version="1.0" encoding="iso-8859-1" ?> <xml> <file poster="John Doe <john@example.com>" date="1301234567" subject="bla bla "filename1.zip" yEnc (1/5)"> <groups> <group>a.b.blabla</group> <group>a.b.dadada</group> </groups> <segments> <segment bytes="100000" number="1">3e5d7d4f336475502b643b466d@example.com</segment> <segment bytes="200000" number="2">272b5c2e3e447a66407b20633d@example.com</segment> <segment bytes="300000" number="3">3e2724613926406d692765446e@example.com</segment> <segment bytes="400000" number="4">213939595c6b51575c43665d48@example.com</segment> <segment bytes="50000" number="5">3366285f6a7b317945405c3b30@example.com</segment> </segments> </file> <file poster="John Doe <john@example.com>" date="1301234678" subject="bla bla "filename2.zip" yEnc (1/5)"> <groups> <group>a.b.blabla</group> <group>a.b.dadada</group> </groups> <segments> <segment bytes="300000" number="1">2c7778262263625f7a64343137@example.com</segment> <segment bytes="400000" number="2">78685e6e7b4339272b7042772c@example.com</segment> <segment bytes="500000" number="3">7a47472e25265a3b6e55214e75@example.com</segment> <segment bytes="600000" number="4">6c4e64784e70384c3e2a2a544e@example.com</segment> <segment bytes="50000" number="5">76695f59277724334035724a22@example.com</segment> </segments> </file> <file poster="John Doe <john@example.com>" date="1301234789" subject="bla bla "filename3.zip" yEnc (1/1)"> <groups> <group>a.b.blabla</group> <group>a.b.dadada</group> </groups> <segments> <segment bytes="200000" number="1">283d4f6f384f417b422f697163@example.com</segment> </segments> </file> </xml> My PHP code: Code: [Select] <?php // read the xml file $xml = simplexml_load_file('demo.xml'); // initialize helper variables $filenum = 0; // loop through all files foreach($xml as $files){ // get the posting date $timestamp = (int)$xml->file[$filenum]->attributes()->date; echo date("Y-m-d H:i:s", $timestamp); echo " - "; // get the filename $subject = $xml->file[$filenum]->attributes()->subject; preg_match("#.*\"(.*)\".*#iu", $subject, $matches); echo $matches[1]; echo " - "; // loop through all segments of file to get total size $segnum = 0; $totalbytes = 0; foreach($xml->file[$filenum] as $segments){ $totalbytes += $xml->file[$filenum]->segments->segment[$segnum]->attributes(); $segnum++; } // end segments echo $totalbytes; echo "<br />\n"; $filenum++; } // end files ?> Current output: Code: [Select] 2011-03-27 16:02:47 - filename1.zip - 300000 2011-03-27 16:04:38 - filename2.zip - 700000 2011-03-27 16:06:29 - filename3.zip - Fatal error: Call to a member function attributes() on a non-object in /var/www/readxml.php on line 28 Thank you very much for your help! This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 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! 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. 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 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 With a database of synonyms, how do I compare a fragment of a texarea sentence split by the php explode function to return only five synonyms out of say 100 synonyms of the same word for each fragment. The Sql statement is queried to return 5 results Code: [Select] <?php if (isset($_GET['submit'])) { $sentence = $_GET['sentence']; // break $sentence using the space character as the delimiter $words = explode(' ', $sentence); //tell the amount of words using the size of the array echo 'The sentence has ' . count($words) . ' words.<br />'; // loop through and print all the words for ($i = 0; $i < count($words); $i++) { echo "Piece $i = $words[$i] <br />"; //echo 'Word ' . $i . ' - ' . $words[$i] . '<br />'; //$words=$_GET['words']; $sel="select * from synonyms where synonym LIKE '%$words[$i]%' limit 3"; $data=mysqli_query($dbc,$sel); $num= mysqli_num_rows($data); if (!$data) { die('<p>Error Retrieving<br/>'. 'Error: ' .mysql_error() . '</p>');} $datalist=mysqli_fetch_assoc($data); $synonym=$datalist['synonym']; ?> I intend to use a 2 texareas: 1. Code: [Select] <textarea name="split_sentence"><?php echo "sentence" ?></textarea> the 1st <texarea> has the original sentence to be split by the explode function. 2. Code: [Select] <textarea name="split_sentence2"><?php echo ("$words[$i] {{$synonym}}?></textarea> the second <texarea> should take the explode fragments compare it with the query above and return five synonyms per word on a SINGLE <textarea> tag. 3. Besides, I keep getting this offset error on the 2nd <texarea> refering to the $words[Si] array element in the 2nd <textarea> Below is the full code: Code: [Select] `<?php //session_start(); // Define database connection constants define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'moby_thesaurus'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>compare_words</title> </head> <body> <table><p> PLEASE ENTER INITIAL SENTENCE </p> <form name="sentences" method="get" action="" > <tr> <td> <textarea name="sentence" id="elm1"></textarea> </td> </tr> <tr> <td> <input name="submit" type="submit" value="Create_Spinable Content" /> </td> </tr> </form> </table> <?php if (isset($_GET['submit'])) { $sentence = $_GET['sentence']; // break $sentence using the space character as the delimiter $words = explode(' ', $sentence); //tell the amount of words using the size of the array echo 'The sentence has ' . count($words) . ' words.<br />'; // loop through and print all the words for ($i = 0; $i < count($words); $i++) { echo "Piece $i = $words[$i] <br />"; //echo 'Word ' . $i . ' - ' . $words[$i] . '<br />'; //$words=$_GET['words']; $sel="select * from synonyms where synonym LIKE '%$words[$i]%' limit 3"; $data=mysqli_query($dbc,$sel); $num= mysqli_num_rows($data); if (!$data) { die('<p>Error Retrieving<br/>'. 'Error: ' .mysql_error() . '</p>');} $datalist=mysqli_fetch_assoc($data); $synonym=$datalist['synonym']; ?> <table><p> SPINABLE CONTENT </p> <form name="sentences" method="get" action="" > <tr> <td> <?php if ($datalist=mysqli_fetch_array($data)) { do{ ?> <textarea cols="80" id="editor1" name="sentence" rows="10"><?php echo ("$words[$i] {{$synonym}}||{{$synonym}}||{{$synonym}}"); ?></textarea> <?php } while ($datalist=mysqli_fetch_array($data)); echo("</table> </p>"); } ?> <?php } } ?> </td> </tr> <tr> <td> <input name="submit" type="submit" value="Spin This Now" /> </td> </tr> </form> </table> </body> </html> Please any suggestions would be highly appreciated. I store date data in MySql in this format DD-MM-YYYY , and now I need to explode this format when get information from database to get this: $day = DD , $month = MM , $year = YYYY. $result = $db->query("SELECT user_birthday FROM users WHERE user_id = " . mysql_real_escape_string($_SESSION['user_id']) . " LIMIT 1"); $row = mysql_fetch_assoc($result); $birthday = $row['user_birthday']; and I get this date format: 12-07-1980 How to explode this 3 values in day, month, year? I'm trying to add options to products. Currently, I have them in this format: Leather reinforced hilt,5.00::Stabbing tip,3.00::Logo,10.00 Code: [Select] $option_results = mysql_query("SELECT product_options FROM products WHERE product_id='".$product."'"); while($option_row = mysql_fetch_array($option_results)){ $option = explode("::", $option_row[0]); $option_part = explode(",", $option[0]); $option_part[0] = $option_name; $option_part[1] = $option_price; echo "<li><a href=\"#\">".$option_name.", Add $".$option_price."</a></li>"; } I would like the output to be: <li><a href="#">Leather reinforced hilt, Add $5.00</a></li> <li><a href="#">Stabbing tip, Add $3.00</a></li> <li><a href="#">Logo, Add $10.00</a></li> Need some help with something I have not done before. I have a dynamic checkbox set up to accept userinput then post $optionsname,$optionsprice. Code: [Select] echo "<li><input type=\"checkbox\" name=\"optionslist[]\" value=\"$optionsname,$optionsprice\" /> $optionsname - $ $optionsprice - $optionsdisc</li>"; So far no problem Code: [Select] $showoptions=$_POST['optionslist']; if(empty($showoptions)) { echo("You didn't select any options."); } else { $N = count($showoptions); echo("<strong>You selected $N options:</strong> "); for($i=0; $i < $N; $i++) { echo("<li>".$showoptions[$i] . "</li>"); } } Can someone tell me how to explode $showoptions into $optionsname,$optionsprice again. Thanks for any help in advanced. Code: [Select] $newrating = round($imageinfo['rating'],2); this outputs: 4.49 in my db rating is 4.4884 all i need is the 4.... would i use some type of preg_replace or something just to grab the first 1 before the decimal? (all i need is the first number before the decimal) 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 I am having a nightmare with an explode and cant get it to work. I am posting a string using JQuery to a PHP form which needs to explode the string into an indexed array to be inserted into a database. This is what the string looks like "importance%5B101%5D=50&importance%5B100%5D=50&importance%5B99%5D=50&importance%5B98%5D=50" The original array has been serialised into the above string. The arrayname is importance. The array's index (inside the square brackets) is referenced from an ID from the page. The square brackets have been replaced by '%5B' and '%5D' and surround the array index by the JQuery. The value for each of these array items is shown as =50. So its basically the same as a GET when we have name=value&name1=value1etc') How would i explode the string above to remove the '%5B' and '%5D' to make the '[' and ']' reappear and then from then it can be read as a GET post? like 'name=value&name1=value1etc'. Using the new array of that index ready to be inserted into a MySQL database. Im going mad trying to solve this!!! I have a script that connects to another server to pull data... When it pulls the data it comes back in the following format: Code: [Select] t1.sh t2.sh t3.sh test.sh However using the code bellow does not separate it like it should, it should put one file per line but I think I did something wrong... Code: [Select] // Pulls the output from the server: $var_test = $ssh->exec('./test.sh'); // Explodes it... $var_test2 = explode(" ", $var_test); // Echos it one per line... foreach ($var_test2 as $variable) { echo '<br>'.$variable; } hi, now i have something like this: $pizza = "piece1 piece2 piece3 piece4"; $one_word = explode(" ", $pizza); but i want to get 2 words together, like that: $two_words[0]='piece1 piece2'; $two_words[1]='piece3 piece4'; $two_words[2]='piece2 piece3'; $two_words[3]='piece1 piece4'; if it's impossible with explode, then it's fine if you use some other function, i don't care as long as it works. thank you, tastro Hi, I have a database that is going to contain recepies and ingredients tables. The recipe table is going to store the ingredients like this: 1,5,6,8 This refers to the table ingredients id. I now want to explode these vaules and count them up so they can be outputted like this: sugar (2) honey(1) flour (3) I have no idea of how to count all of the exploded id's and ouput them like above I am in need of a alimit on the explode() fucntion but reading through the php explode manual on php.net there doesn't seem to be one that is right for me. Basically I'm making a command system for a php chat and it has a command called ban. I have code that find out if it is a command or a normal string, I also have code that starts to break up the command into segments that can be places in the database. I want to split up "ban user lengthID "Reason why you were banned"" using explode($string, " ") but I notice that that will also break up the "reason why you are banned". How do I get it to split up the command but NOT thereason why you were banned string? Confusing I know, Please ask any questions that would help me explain it better Thanks in advance! how to take a word in php or explode based on luas Bangunan :xxx For example I have string $string =" Kondisi Properti : Bagus Dilengkapi Perabotan : Unfurnished Sertifikat : Lainnya Daya Listrik : 2200 Watt Kamar Tidur : 3/1 Kamar Mandi : 2/1 Luas Bangunan : 92 m² Luas Tanah : 126 m² Jumlah Lantai : - Kondisi Properti : Bagus Sekali Dilengkapi Perabotan : Unfurnished Sertifikat : SHM - Sertifikat Hak Milik Daya Listrik : 6600 Watt Saluran Telepon : 1 Garasi : 3 Kamar Tidur : 4/1 Kamar Mandi : 3/1 Luas Bangunan : 300 m² Luas Tanah : 228 m² Jumlah Lantai : 2.5 "; eg I want to take every "Luas bangunan: xxx" Thanks |