I have a csv file containing attributes of the stores (id, name, category, featured, etc) to be displayed in a project. For now I need to display an array of featured stores with the condition 'featured'='TRUE'. There are 10 results.
Here's the code to read the file and save the data as an associative array
function read_all_stores() {
$file_name = 'csv_files/stores.csv';
$fp = fopen($file_name, 'r');
$first = fgetcsv($fp); // get the first row aka headlines of the file
$stores = [];
while ($row = fgetcsv($fp)) {
$i = 0;
$store = [];
foreach ($first as $col_name) {
$store[$col_name] = $row[$i];
$i++;
}
$stores[] = $store;
}
return $stores;
}
sample result of the first 5 stores
Now I want to display only the stores that has attribute featured = 'TRUE'. I tried this code:
function get_store() {
$stores = read_all_stores();
$feature = [];
foreach ($stores as $s) {
while ($s['featured'] == 'TRUE') {
$feature[] = $s;
return $feature;
}
}
return false;
}
But it only returns one result.
I tried removing the single quotation mark but it seems to only accept the 'TRUE' value as string instead of boolean. How can I fix this foreach loop??
$stores[] = $store;. Also, inget_storemethod you are returning as soon as there is a match. I think you should add all of the matched ones into an array and then return at the end of the method.