hi
I need to parse and convert some .csv file data to PHP array. My data might look like:
[CODE]
name,address_one,address_two,address_postcode
Bob,1 A Street,A town,AA11AA
Andy,92 Church St,Manchester,M20 3JN
Sarah,893 London Road,Enfield,EN3 9HB
Freda,67 Green Close,Newcastle,Nw5 2ED
Some of the headers have underscores in them. I need to split these such that the split string would be a sub element of the original string. E.g.
Taking the header ‘address_one’, then split it on ‘_’ and we’d have ‘one’ as a sub-element of address. I want to loop through the entire contents of my data file with my array eventually looking like:
[code=php]
Array
(
[‘name’]=> Bob
[0] => Array
(
[address] => Array
(
[one] => 1 A Street
[two] => A town
[postcode] => WC2 9GH
)
)
[‘name’]=> Andy
[1] => Array
(
[address] => Array
(
[one] => 92 Church St
[two] => Manchester
[postcode] => M20 3JN
)
)
…omitted
)
So headers are the keys/sub keys and the data are the array values.
What I’ve tried thus far:
[code=php]
public function parseFile($fileIn)
{
if (($handle = fopen(“$fileIn”, “r”)) !== FALSE)
{
$lines = file(“$fileIn”);
$headers = explode( ‘,’, “$lines[0]”);
foreach($headers as $header)
{
if($x = strpos(“$header”, ‘_’)){
$child = trim(substr(“$header”, $x), ‘_’);
$parent = substr(“$header”, 0, $x);
print “parent: $childn”;
}
}
fclose($handle);
} else {
throw new Exception(‘Unable to open the file!’);
}
} // parseFile
I figure I’m going to need some temporary arrays combined with PHP array functions. I’ve looked at some of the usual suspects: array_push, array_walk, array_map……etc
Best or easiest way to get the data into this format? Clues, suggestions…
thanks in advance.