2017-08-25 84 views
0

我打開CSV文件和地方數組中的所有值搜索多維數組匹配

例如CSV文件:

Steven King, IT 

Ronald Dahl, BFG 

Charles Abbot, The island 

所以這造成我與不同的鍵陣列ECT爲每個藝術家等。我使用下面的打開了我的CSV文件:

$file = fopen('./example.csv','r') or die("can't open file"); 
while (($line = fgetcsv($file, 1000)) !== false) { 
    $csv[] = $line; 
    } 
fclose($file) or die("can't close file"); 

,工作正常,但我掙扎搜索所有的用戶搜索任何數值數組;我的表單發佈用戶字符串並在數組中搜索與用戶輸入內容相匹配的任何值(不區分大小寫)。即:

//gets the users input from form 
$user_string = $_POST['search_string']; 

比方說,用戶進入斯蒂芬或島嶼,即時通訊試圖讓它搜索$ CSV陣列匹配或包含字符串和輸出該鍵的所有值的任意值。我曾嘗試使用array_filter & preg_grep但沒有太多的運氣。

回答

0

我想你需要數組搜索功能來確認當你在循環中創建$ cvs數組。您可以在此循環中創建結果。這是一個示例。

<?php 

$file = fopen('example.csv', 'r') or die("can't open file"); 

$results = []; // it'll hide php notifications 

$searchword = $_POST['search_string']; 

while (($line = fgetcsv($file, 1000)) !== false) { 

    $found = false; 

    foreach ($line as $var => $val) { 
     if (stristr($val, $searchword) || stristr($var, $searchword)) { 
      $found = true; 
     } 
    } 

    if ($found == true) { 
     $results[] = $line; 
    } 
} 

fclose($file) or die("can't close file"); 

print_r($results); 
+0

謝謝穆罕默德,我仍然有麻煩,把它放在結果數組中。即它打印出一個空數組。我錯過了什麼嗎? – Buzzy

+0

cvs文件是真的嗎?因爲它以點開頭(。) –

+0

對不起,這是我的錯誤,是的,我確實有文件的正確的文件路徑,但它不會將值添加到結果數組,不知道array_search()函數是否工作。 – Buzzy

0

這裏有一個功能的方法:

$f = array_filter($csv, function($cs) use($user_string){ foreach($cs as $c){return stristr($c,$user_string);}}); 

既然你能夠創造從您的CSV文件的數組,簡單地認爲數組傳遞給array_filter,然後遍歷每個陣列使用foreach和使用stristr來返回與您的搜索針相匹配的所有值。

$arr = [ 
0 => [ 
    "name" => "Stephen King", 
    "movie" => "IT" 
    ], 
1 => [ 
    "name" => "Ronald Dahl", 
    "movie" => "BFG" 
    ], 
2 => [ 
    "name" => "Charles Abbot", 
    "movie" => "The Island" 
    ] 
]; 

$n = "Ron"; 

$f = array_filter($arr, function($ar) use($n){ foreach($ar as $a){return stristr($a,$n);}}); 

var_dump($f);