我正在构建一个基于CSV文件进行简单报告的小型应用程序,CSV文件采用以下格式:
DATE+TIME,CLIENTNAME1,HAS REQUEST BLABLA1,UNIQUE ID
DATE+TIME,CLIENTNAME2,HAS REQUEST BLABLA2,UNIQUE ID
DATE+TIME,CLIENTNAME1,HAS REQUEST BLABLA1,UNIQUE ID
DATE+TIME,CLIENTNAME2,HAS REQUEST BLABLA2,UNIQUE ID
现在我正在使用以下函数处理它:
function GetClientNames(){
$file = "backend/AllAlarms.csv";
$lines = file($file);
arsort($lines);
foreach ($lines as $line_num => $line) {
$line_as_array = explode(",", $line);
echo '<li><a href="#"><i class="icon-pencil"></i>' . $line_as_array[1] . '</a></li>';
}
}
我正在尝试仅检索Clientname值,但我只想要唯一值。
我试图创建几种不同的接近这个的方式,我知道我需要使用unique_array函数,但我不知道如何使用这个函数。
我试过这个:
function GetClientNames(){
$file = "backend/AllAlarms.csv";
$lines = file($file);
arsort($lines);
foreach ($lines as $line_num => $line) {
$line_as_array = explode(",", $line);
$line_as_array[1] = unique_array($line_as_array[1]);
echo '<li><a href="#"><i class="icon-pencil"></i>' . $line_as_array[1] . '</a></li>';
}
}
但这给了我一个非常糟糕的结果,包含100个空格而不是正确的数据。
答案 0 :(得分:2)
我建议您在读取csv文件时使用fgetcsv()
函数。在野外csv文件可以通过naive explode()方法处理相当复杂:
// this array will hold the results
$unique_ids = array();
// open the csv file for reading
$fd = fopen('t.csv', 'r');
// read the rows of the csv file, every row returned as an array
while ($row = fgetcsv($fd)) {
// change the 3 to the column you want
// using the keys of arrays to make final values unique since php
// arrays cant contain duplicate keys
$unique_ids[$row[3]] = true;
}
var_dump(array_keys($unique_ids));
您也可以稍后收集值并使用array_unique()
。您可能希望将&#34;读入&#34; 和&#34;写出&#34; 部分代码。
答案 1 :(得分:0)
尝试使用array_unique()