I'm using PHP 5.3+ and trying to open a CSV file, store the information as an associative array and then be able to filter the array.
So far i have managed to open the CSV file using (feel free to improve):
$all_rows = array();
$header = null;
if (($handle = fopen("files/my_data.csv", "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($header === null) {
$header = $row;
continue;
}
$all_rows[] = array_combine($header, $row);
}
fclose($handle);
}
print_r($all_rows);
Which prints the data ok, but I am struggling to work out how to do something like the following...
For each Row, where Column 1 is greater than or equal to 1.0 and less than 3.9 Count then Output the Total. In the following example data 2 out of 3 rows would meet the criteria.
Example Data Only:
/*
$row_1 = [
['col_1' => '1.1', 'col_2' => 'Product Name'],
];
$row_2 = [
['col_1' => '1.2', 'col_2' => 'Product Name'],
];
$row_3 = [
['col_1' => '4.0', 'col_2' => 'Product Name'],
];
*/
$row_1, 2, 3 and $col_1, 2 ,3 etc would be the names listed in the associative array.
Any help would be appreciated, if you need any further information please ask
Thanks
James
=============================
UPDATE: Here is the foreach statements
$counter_total = 0;
// Count Sidebar Products Positions
foreach ($all_rows as $key => $value) {
// I was missing the $key value in $all_rows[{here}]['ProductPosition']
#echo $key; // ID Number of Row
$counter_total++;
if (($all_rows[$key]['ProductPosition'] >= 1) && ($all_rows[$key]['ProductPosition'] <= 9.9)){
$sidebar_one++;
}
elseif (($all_rows[$key]['ProductPosition'] >= 10) && ($all_rows[$key]['ProductPosition'] <= 19.9)){
$sidebar_two++;
}
elseif (($all_rows[$key]['ProductPosition'] >= 20) && ($all_rows[$key]['ProductPosition'] <= 29.9)){
$sidebar_three++;
}
}
// Display Output - Testing Only
echo '==================<br>';
echo 'Counter Total: '. $counter_total . '<br>';
echo 'Sidebar 1: '. $sidebar_one . '<br>';
echo 'Sidebar Page 2: '. $sidebar_page_two . '<br>';
echo 'Sidebar Page 3: '. $sidebar_page_three . '<br>';
// Show Sidebar 1 Products
foreach ($all_rows as $key => $value) {
if (($all_rows[$key]['ProductPosition'] >= 1) && ($all_rows[$key]['ProductPosition'] <= 9.9)){
#$sidebar_one++;
echo $key . ': ' . $all_rows[$key]['Queries']."<br />";
}
}
However, the Show Sidebar 1 Products shows all products and ignores the counter, even though the counter in the test display was correct? Baffled!!
foreach()loop to iterate over the contents of$all_rows. In the loop, test the columns you want and accumulate the result in a variable.ifstatement? Adding a number to a variable to get a total?foreach()you don't need to write$all_rows[$key], you can use$valueinstead. That's the point of usingforeach.