2016-07-26 60 views
0

目前,我的代碼搜索數據,但您需要鍵入全名來顯示結果。我想我需要將我的全名分爲名字和姓氏。所以無論是可以搜索和發現。PHP - 搜索名字以及全名

我希望它按全名或姓

-I需要它爲名字的人顯示結果查找和顯示文件。但是在我的csv文件(這是存儲數據的地方)中,全名被存儲爲例如。 「鮑勃傑拉德」

我猜我需要分離循環中的值以搜索名字以及?我不太確定..任何幫助將不勝感激。

以下是我有:

//This gathers the values from the form (search bar) and assigns it to the variable $SearchThis 
//isset() 
$SearchThis = isset($_POST['Search']) ? $_POST['Search'] : ''; 
//empty() 
$SearchThis = !empty($_POST['Search']) ? $_POST['Search'] : ''; 



// Grabs the csv file (and its existing data) and makes it into an array 
$csv = array(); 
$lines = file('data/StaffData.csv', FILE_IGNORE_NEW_LINES); 
foreach ($lines as $key => $value) 
{ 
    $csv[$key] = str_getcsv($value); 
} 



//A new array which will display the search results 
$new_csv = array(); 

//This displays which rows have matched the search (it is put in an array) 

//Looks through full names 
$keys = array_keys(array_column($csv, 0), $SearchThis); // original code 
foreach($keys as $index) {        // Iterate over the keys 
    $new_csv[] = $csv[$index];       // Copy the matching rows to our new array 
} 
//Looks through phone numbers 
$keys = array_keys(array_column($csv, 1), $SearchThis); // original code 
foreach($keys as $index) {        // Iterate over the keys 
    $new_csv[] = $csv[$index];       // Copy the matching rows to our new array 
} 
//Looks through gender 
$keys = array_keys(array_column($csv, 2), $SearchThis); // original code 
foreach($keys as $index) {        // Iterate over the keys 
    $new_csv[] = $csv[$index];       // Copy the matching rows to our new array 
} 
//Looks through Birthday 
$keys = array_keys(array_column($csv, 3), $SearchThis); // original code 
foreach($keys as $index) {        // Iterate over the keys 
    $new_csv[] = $csv[$index];       // Copy the matching rows to our new array 
} 

//Looks through Type of work 
$keys = array_keys(array_column($csv, 4), $SearchThis); // original code 
foreach($keys as $index) {        // Iterate over the keys 
    $new_csv[] = $csv[$index];       // Copy the matching rows to our new array 
} 

回答

1

請使用在fullname欄搜索:

$new_csv = array_filter($csv, function ($item) use($SearchThis) { 
    //Match the full name 
    if ($item[0] === $SearchThis) { 
     return true; 
    } 
    //Split the fullname by space characters into array 
    //and see if it contains the $SearchThis 
    return in_array($SearchThis, preg_split("/[\s]+/", $item[0])); 
}); 

我希望這會幫助你。

+0

你傳奇!這正是我所追求的。發揮魅力。我喜歡它的方式,因爲它對我來說很有意義。 謝謝, –