简体   繁体   English

PHP计数字符串显示为数组内的值的次数

[英]PHP Count Number of Times A String Appears As A Value Inside An Array

So I looked around here for a bit but cant seem to get this right, so I am forced to make a new post. 因此,我在这里环顾了一下,但似乎无法正确处理此事,因此我被迫发表新文章。 I gave it an effort! 我付出了努力! Don't hurt me. 别伤害我

Sample Array: 样本数组:

$ndata = Array
(
    [ARMOR_HEAD] => Andariel's Visage
    [ARMOR_TORSO] => Blackthorne's Surcoat
    [ARMOR_FEET] => Illusory Boots
    [ARMOR_HANDS] => Gauntlets of Akkhan
    [ARMOR_SHOULDERS] => Pauldrons of Akkhan
    [ARMOR_LEGS] => Blackthorne's Jousting Mail
    [ARMOR_BRACERS] => Nemesis Bracers
    [ARMOR_MAINHAND] => Gyrfalcon's Foote
    [ARMOR_OFFHAND] => Jekangbord
    [ARMOR_WAIST] => Blackthorne's Notched Belt
    [ARMOR_RRING] => Ring of Royal Grandeur
    [ARMOR_LRING] => Stone of Jordan
    [ARMOR_NECK] => Kymbo's Gold
)

  $count = count(preg_grep('Akkhan', $ndata));
  print_r($count);

So this is only returns 1 instead of 2. I also tried array_search() , but that simply returns a the first found with its key. 因此,这仅返回1而不是2。我也尝试了array_search() ,但是它只是返回一个第一个带有其键的值。 Or in_array but that is just boolean I guess.. Is there a better way to go about this? 还是in_array但是我猜这只是布尔值。是否有更好的方法来解决这个问题?

The first parameter to preg_grep is not a string, it is a regular expression pattern represented as a string. preg_grep的第一个参数不是字符串,而是表示为字符串的正则表达式模式。 Try this: 尝试这个:

preg_grep('/Akkhan/i', $ndata)

For more information, see the documentation page for preg_grep . 有关更多信息,请参见preg_grep的文档页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM