我有一个这样的文本文件:
unfinished unfinished 17876 open peters Current/17876 -
unfinished unfinished 17830 new peters Current/17830 -
unfinished unfinished 17810 new jongr Current/17810 -
我想列出第5栏中的所有项目。但是如果有重复,我不希望它被列出两次。我到目前为止的代码是:
<select>
<?php
ini_set('display_errors',"1");
$lines = file('C://projectlist/project-list.txt');
foreach ($lines as $line){
$parts = explode(' ', $line);
echo "<option>{$parts[4]}</option>";
}
?>
</select>
但是,这只列出了下拉框中的所有名称。
答案 0 :(得分:3)
尝试使用array_unique();
一个例子:
$my_array = array_unique($my_array);
或使用帖子中的细节的其他解决方案:
<?php
ini_set('display_errors',"1");
$select = '<select>';
$lines = file('project-list.txt');
$fifth_column = array();
foreach ($lines as $line){
$parts = preg_split('/\s+/', $line);
$count = 0;
foreach ($parts as $partVal){
if ((in_array($partVal, $fifth_column) == FALSE) && $count == 4){
$fifth_column[] = $partVal;
}
$count++;
}
}
foreach($fifth_column as $value){
$select .= "<option value='".$value."'>".$value."</option>";
}
$select .= '</select>';
echo $select;
?>
答案 1 :(得分:0)
这是一个不错的小功能。你可以阅读它here。
以下是一个例子:http://3v4l.org/uGgU4
function doopScooper($dataArray, $uniqueKeys){
// store the the previously checked sub-arrays here
$checked = array();
//loop through the array
foreach($dataArray as $k=>$row){
// this will become the sub array that needs to be checked
$checkArray = array();
//create the sub array for comparison
foreach($uniqueKeys as $key)
$checkArray[$key] = isset($row[$key]) ? $row[$key] : NULL;
// convert sub array to string for easy comparison
$checkArray = json_encode($checkArray);
// check for duplicates, if found delete, else add to the checking array
if(in_array($checkArray, $checked)) unset($dataArray[$k]);
else $checked[] = $checkArray;
}
return $dataArray;
}
$lines = "unfinished unfinished 17876 open peters Current/17876 -
unfinished unfinished 17830 new peters Current/17830 -
unfinished unfinished 17810 new jongr Current/17810 -";
$lines = explode("\n",$lines);
$parts=[];
foreach ($lines as $line) $parts[] = explode(' ', $line);
//remove duplicates from the 7th column
$lines = doopScooper($parts, array(7));
foreach ($lines as $line) echo "<option>{$parts[4]}</option>";