2016-05-24 29 views
0

我想要查找數組中特定字母的出現,並且還要計算出現數值的次數。 例如:找到數組值中特定字母的出現

<?php 
$aa= array (
    'sayhello', 
    'hellostackoverflow', 
    'ahelloworld', 
    'foobarbas' 
    'apple' 
); 

這裏,如果我搜索的「o」,那麼它應該返回4作爲「O」的存在只有四個值

回答

1

試試這個代碼這是爲我工作。

<?php 
$input = preg_quote('o', '~'); // don't forget to quote input string! 
$data = array (
    'sayhello', 
    'hellostackoverflow', 
    'ahelloworld', 
    'foobarbas', 
    'apple' 
); 

$result = preg_grep('~' . $input . '~', $data); 
echo count($result); // return the number of element 

echo '<pre>'; 
print_r($result); 
exit; 
?> 

我希望這對你有用。在這種結構

function array_seaech($array, $search) 
    { 
     $count = 0; 
     foreach($array as $key => $value) 
     { 
      if(strpos($value, $search)) 
       $count++; 
     } 

     return $count; 
    } 

我們檢查數組的所有節點,並檢查該字符串存在與否:

+0

非常感謝。如預期的那樣得到 –

+0

很高興聽到這是爲你工作 –

0

陣列可以只是被壓平爲字符串對於所有意圖和目的。

$occurences = substr_count((string)$aa, 'o'); 

$ occurences然後是4

0

你可以從這個結構使用。

相關問題