【问题标题】:How do I get only unique values from CSV file array如何仅从 CSV 文件数组中获取唯一值
【发布时间】:2014-09-12 21:25:56
【问题描述】:

我正在构建一个基于 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 个空格而不是正确的数据。

【问题讨论】:

    标签: php html arrays sorting csv


    【解决方案1】:

    我建议您在读取 ​​csv 文件时使用fgetcsv() 函数。在野外 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));
    

    您还可以收集值并稍后在其上使用array_unique()。您可能也想拆分代码的 “读入”“写出” 部分。

    【讨论】:

    • 谢谢,这个答案效果很好:) 现在我还需要拆分一些数据,但这是一个不同的问题。
    【解决方案2】:

    尝试使用array_unique()

    文档: http://php.net/manual/en/function.array-unique.php

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多