php:使用google csv,删除列中填充的重复值

时间:2012-05-05 20:36:21

标签: php csv array-unique

我是php的新手,一直在不知疲倦地寻找解决这个问题的方法(我打赌它是一个超级简单的解决方案*叹息)。

我正在从google doc导入.csv Feed。它提取了2列,一个用于"名称"和另一个"位置"。我想删除重复的"位置"。因为我使用fgetcsv,我的理解是它已经将数据排序到一个数组中。理想情况下,它会省略" location"重复,以便"名称"看起来好像被列在"位置"它们对应于。

这就是我所拥有的:

    $url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
    $handle = fopen($url, "r");
    while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
    echo "<li>\n";
    echo $data[1];
    echo "<br/>\n";
    echo $data[2];
    echo "</li>\n";
    }
    fclose($handle);

理想情况下,我可以使用以下内容:

    $url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
    $handle = fopen($url, "r");
    while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
    echo "<li>\n";
    echo array_unique($data[1]);
    echo "<br/>\n";
    echo $data[2];
    echo "</li>\n";
    }
    fclose($handle);

非常感谢您的任何帮助! :O)

2 个答案:

答案 0 :(得分:0)

这可能有效,假设数组中的项目按位置分组。它存储最后一个数据项(位置)并比较每个项目是否具有该位置。如果是,则打印它,否则它会创建一个带有新位置的新列表项,然后打印下面的名称(我还没有测试过):

$url = "the-url-to-my-csv-feed";
$handle = fopen($url, "r");
$lastdata = '';
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
    if ($lastdata == '') {
        echo "<li><strong>" . $data[1] . "</strong>\n";
        echo "<br/>\n";
        $lastdata = $data[1];
    }

    if ($lastdata != $data[1]) {
        echo "</li>\n";
        echo "<li><strong>" . $data[1] . "</strong>\n";
        echo "<br/>\n";
        $lastdata == $data[1];
    }
    echo $data[2] . "<br/>\n";
}
fclose($handle);

答案 1 :(得分:0)

<? //PHP 5.4+
$url = 'url to your csv feed';

//Group people by same location first,
//not assuming csv is already sorted.
$namesByLocations = [];
//Because we're using \SplFileObject, when the reference goes out
//of scope at the end of the loop, the file pointer is never
//left open. This is true even if an exception is thrown
//in the middle of looping.
foreach(
    \call_user_function(static function() use ($url){
        $file = new \SplFileObject($url);
        $file->setFlags(\SplFileObject::READ_CSV);
        return $file;
    })
    as $array
){
    //$array[1] is assumed to be location string
    //$array[2] is assumed to be a name that is there.
    $namesByLocations[$array[1]][] = $array[2];
}


foreach($namesByLocations as $location => $names){
    //Protect against injection flaws,
    //escape to destination's context. (html this time)
    echo '<strong>' . \htmlspecialchars($location) . '</strong>';
    echo '<ul>';
    foreach($names as $name){
        echo '<li>' . \htmlspecialchars($name) . '</li>';
    }
    echo '</ul>';
}
?>