简体   繁体   中英

Displaying data from a CSV file with multi-dimensional PHP array

I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...

Using this example from php -

<?php 
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
    $a = array_combine($csv[0], $a);
});

array_shift($csv);

foreach($csv as $car){
    foreach($car as $key=>$value){
        echo "<div id='car'>".$key.":".$value."</div></br>";
    }
}
?>

This is the array I get -

BodyStyle:"Station Wagon"

"DaysInStock":"27"

"Make":"Toyota"

"Model":"Prius v"

"MSRP":"0"

"SellingPrice":"26995"

"StockNumber":"387515"

"Trim":"Three"

"VIN":"JTDZN3EU9E3306528"

"Year" :"2014"

Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?

I have tried this:

print_r ($csv[0]['Make']; 
echo $csv[0]['Make'];

Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.

From here how would I strip the quotes and break out each value?

This is the error being thrown - Invalid argument supplied for foreach() in

Thanks in advance!

foreach($csv as $car){
    echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}

alternatively:

foreach($csv as $car){
    foreach($car as $key=>$value){
        echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
    }
}

alternatively:

echo $csv[0]['Make'];

Try this one :

print_r ($csv[0]['Make']);

Basically the $csv variable is an array, to get its values you have to use the loop function, something like :

foreach ($csv as $data) {
    foreach ($data as $index => $value) {
        if ($index == "make") {
            echo $value;
        }
    }
}

If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value). Try it and you'll see :) PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.

So I figured out that I only need 1 foreach loop like so -

foreach($csv as $car){
    $type = $car[0];
    $echo $type;
}

Works now and thanks all for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM