Re: file/array manipulation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Mignon Hunter wrote:
Hello

Hello Hello Hello (and 1 extra Hello just in case you decide to post the same question for a fourth time)


I'm trying to manipulate a text(.csv) file using php. I've read the file and can print each line, but I need to write where column A is missing

ColumnA    ColumnB

R                ABC company
                  ABC company
                  ABC company
                  ABC company
O                XYZ company
                   XYZ company
                   XYZ company
                   XYZ company

What I need to do is write a while loop (I think) to interate through the lines and populate ColumnA while ColumnB equals $var (ABC company then XYZ company), so that I end up with:

ColumnA    ColumnB

R                ABC company
R                ABC company
R                ABC company
R                ABC company
O                XYZ company
O                XYZ company
O                XYZ company
O                XYZ company

Is this possible. What I've got so far to print out the file:

$lines = file('test2.csv');

this function is where you want to start: fgetcsv()




// Loop through our array, and show line and numbers too. foreach ($lines as $line_num => $line) {

assuming you are not going to use fgetcsv() then you need to split $line into seperate 'bits', for which the explode() function is probably going to help. lets assume you have figured out how to use explode()... in which case you if you explode() $line you should have an array of which the first item is the value for ColumnA in the current line.... if that item is empty replace it with the value of ColumnA from the previous line (which you will have to store in a temp var), also you will have to check whether the value for ColumnB has changed - maybe its easier to parse the file twice, on the first iteration you build up an array of all the distinct values in columnB and the proper matching value in columnA - such an array can then be used as a lookup.

// example of array structure you would have to build:
$arr = array(
	'ABC company' => 'R',
	'XYZ company' => 'O',
);

// example of looking up the proper value

$row = explode("\t", $line);
if (empty($row[ 0 ])) {
	// columnA is empty
	$row[ 0 ] = $arr[ $row[ 1 ] ];
}

// example of outputting the array that represents a row
echo join("\t", $row);

  echo "Line #<b>{$line_num}</b> : " . $line . "<br />\n";
}


Thanks in advance


-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux