Reputation: 47
I am using a working function that perfectly displays the contents of a csv file.
function csv2array( $filename, $delimiter )
{
// read the CSV lines into a numerically indexed array
$all_lines = @file($filename);
if( !$all_lines )
{
return FALSE;
}
$csv = array_map( function( &$line ) use ( $delimiter )
{
return str_getcsv( $line, $delimiter );
}, $all_lines );
// use the first row's values as keys for all other rows
array_walk( $csv, function( &$a ) use ( $csv )
{
$a = array_combine( $csv[0], $a );
});
array_shift( $csv ); // remove column header row
return $csv;
}
$items = csv2array( 'filetest.csv', ';' );
//print_r( $items );
echo '<pre>';
var_dump( $items );
echo '</pre>';
The var_dump output is perfect and displays:
array(40) {
[0]=>
array(4) {
["Jurisdiction"]=>
string(2) "AL"
[" Total Distance(mi.)"]=>
string(7) "1730.68"
[" Off Road(mi.)"]=>
string(4) "2.63"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[1]=>
array(4) {
["Jurisdiction"]=>
string(2) "AR"
[" Total Distance(mi.)"]=>
string(6) "826.27"
[" Off Road(mi.)"]=>
string(4) "1.35"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[2]=>
array(4) {
["Jurisdiction"]=>
string(2) "DE"
[" Total Distance(mi.)"]=>
string(5) "49.11"
[" Off Road(mi.)"]=>
string(4) "0.34"
[" Toll Road(mi.)"]=>
string(4) "6.57"
}
I am trying to display the values of those $rows which sounds super easy but I am getting empty values and searched the internet and cannot find the right way to do it. Here is my code:
foreach($items as $row)
{
echo $row[0]. " ".$row[1]." ".$row[2]."TESTTEST<br>";
}
but I only get the TESTTEST results but the total number of times it displays TESTTEST is correct but the values are empty so what am I missing? I searched this site and others and they seem easy but mine isn't working. Thanks.
Upvotes: 0
Views: 43
Reputation: 47
Thanks for the help everyone I got it the way I want and can expand from here on out. I was looking for this code:
$i = 0;
foreach($items as $row)
{
echo $row['Jurisdiction'] . $row[' Total Distance(mi.)'] . "TESTTEST<br>";
$i++;
}
echo 'total: ' . $i;
I will be sure to trim out the space on the names.
Upvotes: 0
Reputation: 23958
What you could do is nest the loop or implode it.
Nesting:
foreach($items as $row)
{
foreach($row as $val){
echo $val . " ";
}
echo "TESTTEST<br>";
}
Or implode:
foreach($items as $row)
{
echo implode(" ", $row);
echo "TESTTEST<br>";
}
Upvotes: 2