Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jan Roels
2,308 PointsBest way importing matrix (2D array) csv file ( PHP )
Hi,
I'm working on a php project that uses a mysql database with all kinds of food ingredients.
I'm able to search the list of ingredients in a searchbox but now i need to compare the selected ingredient with data from a matrix, the matrix is inside a csv-file.
Is it best to import the file into a 2D array or should put it inside the mysql database? The size of the matrix is 300 x 300.
Is there an easy way to import it into a 2D array?
Kind regards,
Jan
2 Answers
Stone Preston
42,016 Pointsyou can use fgetscsv for importing data from a csv. see this stack overflow post for examples on how to do what you are asking
Jan Roels
2,308 PointsThx!
Following code worked to read the csv-file:
$array = $fields = array(); $i = 0;
$handle = @fopen("modelmatrix2.csv", "r");
if ($handle) {
while (($row = fgetcsv($handle, 8192, ';')) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
Now if i run the following code:
foreach($array as $key => $value) {
echo "rowname:". $key . '<br />';
$count = 1;
foreach($value as $cat_name => $values_arr) {
echo $count.": ";
echo "Ingredient: ".$cat_name . ' - Value: ' . $values_arr . '<br /><br />';
$count++;
}
}
I get the following output:
rowname:0
1: Ingredient: - Value: almond
2: Ingredient: almond - Value: 0.368
3: Ingredient: apple -Value: -4.2E-06
The value of ingredient 1 is empty because the the cells in the first row and column of the file contain the names of the ingredients so the first cell in the csv file is empty.
Like this:
(empty) - almond - apple - ... - ....
almond - (values) - (values) - ...
apple - (values) - (values) - ...
Is it possible to instead of 'rowname' being 0 the rowname is the name of the ingredient in the first column? So the output would be like this:
rowname: almond
1: Ingredient: almond - Value: 0.368
2: Ingredient: apple -Value: -4.2E-06
You understand what i mean?