Reputation: 35
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??
Upvotes: 1
Views: 1448
Reputation: 147176
Your problem is that as soon as you find a matching result: $s['featured'] == 'TRUE'
, you return it: return $feature;
. Instead, you need to process all values in $stores
before returning your result. If there are matching stores (count($feature)
is non-zero i.e. truthy), return them, otherwise return false.
function get_store() {
$stores = read_all_stores();
$feature = [];
foreach ($stores as $s) {
if ($s['featured'] == 'TRUE') {
$feature[] = $s;
}
}
return count($feature) ? $feature : false;
}
Upvotes: 1
Reputation: 4289
Two problems in your code:
get_store()
method you are returning as soon as you find a match. Instead you should add all the matched ones and then return at the end.if
instead of while
Here is the modified version of your code:
<?php
function read_all_stores() {
$file_name = '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;
}
function get_store() {
$stores = read_all_stores();
$feature = [];
foreach ($stores as $s) {
if ($s['featured'] == 'TRUE') {
$feature[] = $s;
}
}
return $feature;
}
echo count(get_store());
Upvotes: 0