我使用PHP 5.3+并尝试打开CSV文件,将信息存储为关联数组,然后能够过滤数组。
到目前为止,我已设法使用(随意改进)打开CSV文件:
$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);
打印数据确定,但我正在努力解决如何做以下事情......
对于每一行,其中第1列大于或等于1.0且小于3.9计数,则输出总计。在以下示例中,3行中的2个数据符合标准。
仅限示例数据:
/*
$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和$ col_1,2,3等将是关联数组中列出的名称。
任何帮助将不胜感激,如果您需要任何进一步的信息,请询问
由于
詹姆斯
=============================
更新:这是foreach声明
$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 />";
}
}
但是,显示侧边栏1产品显示所有产品并忽略计数器,即使测试显示中的计数器是正确的?折流板!!
答案 0 :(得分:1)
只需使用一个简单的foreach
循环来测试列并将其添加到总计中。
<?php
$all_rows = [
['ProductPosition' => '1.1', 'Queries' => 'Product 1'],
['ProductPosition' => '1.2', 'Queries' => 'Product 2'],
['ProductPosition' => '4.0', 'Queries' => 'Product 3'],
];
$counter_total = 0;
$sidebar_one = $sidebar_two = $sidebar_three = 0;
// Count Sidebar Products Positions
foreach ($all_rows as $value) {
$counter_total++;
if ($value['ProductPosition'] >= 1 && $value['ProductPosition'] <= 3.9){
$sidebar_one++;
}
elseif ($value['ProductPosition'] <= 19.9){
$sidebar_two++;
}
elseif ($value['ProductPosition'] <= 29.9){
$sidebar_three++;
}
}
// Display Output - Testing Only
echo '==================<br>' . "\n";
echo 'Counter Total: '. $counter_total . '<br>'. "\n";
echo 'Sidebar 1: '. $sidebar_one . '<br>'. "\n";
echo 'Sidebar Page 2: '. $sidebar_two . '<br>'. "\n";
echo 'Sidebar Page 3: '. $sidebar_three . '<br>'. "\n";
foreach ($all_rows as $key => $value) {
if ($value['ProductPosition'] >= 1 && $value['ProductPosition'] <= 3.9){
echo $key . ': ' . $value['Queries']."<br />\n";
}
}