PHP Scripting - Foreach line (of data)
This is an open discussion with 6 replies, filed under General.
Search
I think you'll want to run an initial preg_split
using the source data's newline character, then loop through it with the working code sample you posted.
Could you give me an example of this syntax ashooner?
When I said I'm a noob in PHP I meant it! lol
<?php $data = "0001 01/10/2011 CLIENT X 100,00 0001 01/10/2011 CLIENT X 100,00"; $list = explode("\n",$data); foreach($list AS $data) { $array = preg_split("/[\t]+/",$data); if(count($data) > 3) { // ignore empty/too short lines echo "Document: " . $array[0] . "<br/>"; echo "Date: " . $array[1] . "<br/>"; echo "Client: " . $array[2] . "<br/>"; echo "Value: " . $array[3]; } }
Thanks phoque
One weird thing is according to print_r($array);
all the indexes are 0, so $array[1]
(and so on) returns an error :/
Array ( [0] => 0001 01/10/2011 CLIENT X 100,00 ) Array ( [0] => 0002 05/10/2011 CLIENT Y 150,00 ) Array ( [0] => 0003 10/10/2011 CLIENT Z 120,00 )
It seems that the regex on preg_slip it's not working well after the explode. Maybe I should try to replace the whitespaces with colons, explode by linebreak and then use the regex spliting by colons. I'll give it try..
Made it!
Just for the record, ended up like this
<?php //Raw data separeted with tabs and linebreaks $raw = "0001 01/10/2011 CLIENT X 100,00 0002 05/10/2011 CLIENT Y 150,00 0003 10/10/2011 CLIENT Z 120,00"; //Replacing tabs for colons $data = preg_replace("/[t]+/",":",$raw); //Separating each line to be read by foreach $list = explode("n",$data); //Just icing xD echo "<hr/>"; //Rendering the separeted data from each line foreach($list AS $data) { $array = preg_split("/:/",$data); echo "Document: " . $array[0] . "<br/>"; echo "Date: " . $array[1] . "<br/>"; echo "Client: " . $array[2] . "<br/>"; echo "Value: " . $array[3] . "<hr/>"; } ?>
Big thanks to ashooner and phoque
Create an account or sign in to comment.
I'm creating a little web app for client here found my self needing to do some PHP scripting, but I'm kinda noob on PHP and as I'm familiarized with you guys I decided to ask for help here. The problem is:
I have this data
And I need to render it like this
I've already managed to do this with only one line of data by doing the following
But turns out I just can't figure out how to do this with multiple lines of data.
Any ideas?
*Sorry for the Off-Topic anyway...