2017-03-02 43 views
1

從數組值顯示它的位置我有一組陣列數據的我需要從該陣列找出匹配字和使用PHP

的值
$my_word = 'mbusa.com'; 

$array_data = array:6 [ 
    0 => array:2 [ 
    0 => "Mercedes-Benz Luxury Cars: Sedans, SUVs, Coupes and Wagons" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fwww.mbusa.com%2Fmercedes%2Findex" 
    ] 
    1 => array:2 [ 
    0 => "Mercedes-Benz - International Corporate Website" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fwww.mercedes%2Dbenz.com%2F" 
    ] 
    2 => array:2 [ 
    0 => "New Mercedes-Benz Cars - Autotrader" 
    1 => "/l/?kh=-1&uddg=http%3A%2F%2Fwww.autotrader.com%2FMercedes%2BBenz%2Dcars.jsp" 
    ] 
    3 => array:2 [ 
    0 => "Mercedes-Benz C-Class - mbusa.com" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fwww.mbusa.com%2Fmercedes%2Fvehicles" 
    ] 
    4 => array:2 [ 
    0 => "Mercedes-Benz - New models: Pricing, MPG, and Ratings | Cars.com" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fwww.cars.com%2Fresearch%2Fmercedes_benz%2F" 
    ] 
    5 => array:2 [ 
    0 => "Mercedes-Benz Reviews - Mercedes-Benz Cars | Edmunds" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fwww.edmunds.com%2Fmercedes%2Dbenz%2F" 
    ] 
    6 => array:2 [ 
    0 => "Mercedes-Benz - Wikipedia" 
    1 => "/l/?kh=-1&uddg=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMercedes%2DBenz" 
    ] 
    ] 

在該陣列中找出匹配詞,我需要找到my_word並需要顯示位置mbusa.com found at N position

我米用下面的代碼

$matches = array_filter($array_data, function($var) use ($my_word){ 

    return preg_match("/\b$my_word\b/i", $var); 

}); 

試圖但它給錯誤等

的preg_match()預計參數2爲字符串,數組給定

任何建議請 ?

謝謝。

+0

迭代$ array_data並比較$ my_word和$ array_data [i] [1]的值。我不確定在PHP中的確切語法。 –

+0

N postition的意思是? –

+0

我需要知道myword匹配的位置 – 06011991

回答

2

你可以像下面: -

foreach ($array_data as $key=>$val){ 
    foreach ($val as $key1=>$v){ 
     if(strpos($v,$my_word)!==false){ 
      echo 'match position is $array_data['.$key."][".$key1."]"; 
      echo PHP_EOL; 
     } 
    } 
} 

輸出: - https://eval.in/745846

+0

5367683很高興爲您效勞。 –

+0

感謝您的幫助。在這裏代碼中的一個小問題我的網址即將到來像'/ l /?kh = -1&uddg = https%3A%2F%2Fwww.mbusa.com%2Fmercedes%2Findex'但我的實際網址是https:// www .mbusa.com/mercedes/index'。但是,如何在我的視圖中以實際格式打印此文件。建議請。 – 06011991

+0

閱讀關於'urldecode()'和'urlencode()'功能在php –

0

你可以用它來尋找其他內一個字符串出現的對strpos功能:

$text = "/l/?kh=-1&uddg=https%3A%2F%2Fwww.mbusa.com%2Fmercedes%2Findex"; 

if (strpos($text, 'mbusa') !== false) { 
    echo 'true'; 
} 
+0

我需要遍歷整個數組。 – 06011991

1

這樣,你可以這樣做:

$count = 0; 

for ($i = 0; $i < count($array_data); $i++) { 
    for ($j = 0; $j < count($array_data[$i]); $j++) { 
     if (strpos($array_data[$i][$j], 'mbusa') !== false) { 
      echo "Found at Postion ".$j."<br>"; 
      echo $count++; 
     } 
    } 
} 
echo "Found " . $count . "Times";