0

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

我正在从谷歌文档导入 .csv 提要。它拉入两列,一列用于“名称”,另一列用于“位置”。我想删除重复的“位置”。因为我使用的是 fgetcsv,所以我的理解是它已经将数据排序到一个数组中。理想情况下,它将省略“位置”重复项,以便“名称”看起来好像它们列在它们对应的“位置”下。

这是我所拥有的:

    $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)

4

2 回答 2

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>';
}
?>
于 2012-05-05T21:15:23.377 回答
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);
于 2012-05-05T20:45:42.850 回答