2015-06-23 55 views
1

我有一個文本文件是這樣的:請從下拉列表中重複PHP

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> 

但是,這只是在下拉框中列出所有名稱。

+1

也許你應該先寫第5列到一個單獨的數組,然後使用該數組生成下拉列表。您可以使用'array_key_exists()'作爲該數組,在將名稱添加到數組之前檢查該數組中是否存在該名稱。 – Maximus2012

+0

已發佈一個完整的答案Amy –

回答

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

1. *試試*如何? 2. OP應該如何處理它,他爲什麼要使用它? – Rizier123

+0

@ Rizier123現在將添加示例 –

+0

謝謝@ Rizier123和@ 1「一個示例將有所幫助 – Amy

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>"; 
+0

謝謝@Adelphia我會研究這個 – Amy