DM-*_*ion 4 html php csv arrays sorting
我正在构建一个小型应用程序,它基于 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
Run Code Online (Sandbox Code Playgroud)
现在我正在使用以下函数处理这个问题:
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>';
}
}
Run Code Online (Sandbox Code Playgroud)
我试图仅检索 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>';
}
}
Run Code Online (Sandbox Code Playgroud)
但这给了我一个非常非常脏的结果,有数百个空格而不是正确的数据。
fgetcsv()我建议您在读取 csv 文件时使用该函数。在野外,csv 文件可以通过简单的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));
Run Code Online (Sandbox Code Playgroud)
您还可以收集值并array_unique()在以后使用它们。您可能也想拆分代码的“读入”和“写出”部分。