2016-07-26 70 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

你传奇!这正是我所追求的。发挥魅力。我喜欢它的方式,因为它对我来说很有意义。 谢谢, –