Jump to content

noobie csv array question: inserting a return while reading file


jectionpro

Recommended Posts

i have been playing around with php for a few days now, and im really liking it. i am mainly learning it to organize csv info comin from the web.

 

i have a simple problem, and am assuming that there is an easy php function to do what i want, but lack the vocab to look up my own problem.

 

say i have a csv file called test2.csv that is like this:

 

1,2,3,4

5,6,7,8

 

$arrFile = file('test2.csv');
$arrData = array();
for ($i=0;$i<sizeof($arrFile);$i++)
{
        $arrData[$i] = $arrFile[$i];
}

print_r($arrData);

//gives:

Array
(
    [0] => 1,2,3,4,
    [1] => 5,6,7,8,
)

 

 

how can i get the same resulting array if my test2.csv file does not have the return after 4? ie it is:

 

1,2,3,4,5,6,7,8

 

how do i insert a "return" every 4 values? i thought my answer lied in explode() and list(), but i think i am just confusing myself on a simple point. thanks for any help!

 

 

 

 

 

 

So i did come up with one solution, but i dont know if its a very round about way of doing things:

 

essentially i first explode everything, then make a loop to print things out how I want (with an appropriate <br> coming when it should, then export that printout as another csv. here is the code:

 

<pre>
<?php
$arrFile = file('test2.csv');
$arrData = array();

foreach($arrFile as $new)
   {
   	   	$arrData= explode(',', $new, 1000);
   } 

$count=0;
for($i=0;$i<8;$i++)
{
print $arrData[$i].",";
$count = $count+1;
	if($count>3)
	{
		print "<br>";
		$count=0;	
	}
}

?>

</pre>

/*this prints:

1,2,3,4,
5,6,7,8,

I can then export this as a csv. Is this the normal way to go about this problem? thanks!
*/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.