November 28, 20169 yr Hello all, I'm currently converting text from a file and then converting it to an array to display in my browser. I can get the data from the file and using a foreach loop I can convert it into an array, however, I need to convert each word into an array. At the moment I can only convert each line into an array, this line needs to be split up into a name, number and price. For example here's some sample data: John@yahoo.com:7:8.35 Fred@hotmail.com:4:5.59 geoff@gmail.com:3:9.29 I can convert each line in an array but each element must be inserted into its own td inside a table. At the moment I can put each line into a table row but I need to split each element up to: <td>John@yahoo.com</td><td>7</td><td>8.35 at the moment my output is: <td>John@yahoo.com7:8.35</td> Here's a snippet of my code: function display_data($data) { $fh = fopen($data, "r") or die("Unable to open file!"); $content = fread($fh, filesize($data)); $assoc_array = array(); $my_array = explode("\n", $content); sort($my_array); foreach($my_array as $key => $value) { if(is_array($data)) { get_file($value); } elseif(is_object($data)) { get_file($value); } else { $tmp = explode(" ", $value); $tmp = str_replace(array("#",":")," ",$tmp); $assoc_array[$tmp[0]] = $tmp[0]; $this->display_array($assoc_array[$tmp[0]]); } } fclose($fh); } the display_array is simply another function that outputs the code into a table. I know it has to be a explode, preg_split or preg_replace but my reg expression isn't great. Any help? Thanks in advance.
November 28, 20169 yr Aha yeah mate try explode ... $str = "John@yahoo.com:7:8.35"; $new_arry = explode(":", $str);
November 28, 20169 yr Author It doesn't work. I've even hard coded the 'John@yahoo.com:7:8.35' assigned to the variable to make sure it wasn't data from the file but all it does is get rid of anything after the ':' so all you get is the email address everything after it is ignored. Thanks anyway. I'm going to try a nested foreach and see if that works.
November 28, 20169 yr Author Thanks. I've just inserted the explode function into my other function that outputs the table. You're right it works fine. I put the explode function into my foreach loop and it only read the first element as all I was reading was the first element, (line), but when I inserted it into my other function and typed var[0], var[1] and var[2] it works fine thanks.
November 29, 20169 yr It does work, @@BrowserBugs is right. $str = "John@yahoo.com:7:8:35"; $new_arry = explode(":", $str); Will give you: $str = "John@yahoo.com:7:8:35"; $new_arry[0] = John@yahoo.com; $new_arry[1] = 7; $new_arry[2] = 8; $new_arry[3] = 35; Sorry missed to mention that bit :s
Create an account or sign in to comment