Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
搜索数组并返回计数的php函数_Php - Fatal编程技术网

搜索数组并返回计数的php函数

搜索数组并返回计数的php函数,php,Php,我仍然在学习php,并且我已经尝试实现了我在这个网站上看到的类似功能,但是没有任何一个能够正常工作。我想做的是基本的,我想我应该有它,但不能得到它 基本上,我想返回一个字符串在数组中出现的次数 这就是我一直在尝试的。它一直给我0,但应该返回4,因为有4个条目的logoutTime中有May。提前感谢您的支持和指导。当我尝试回显或打印$maycount时,我只得到了0 <?php function MayVPNCount($searchVPNArrayResults, $may){

我仍然在学习php,并且我已经尝试实现了我在这个网站上看到的类似功能,但是没有任何一个能够正常工作。我想做的是基本的,我想我应该有它,但不能得到它

基本上,我想返回一个字符串在数组中出现的次数

这就是我一直在尝试的。它一直给我0,但应该返回4,因为有4个条目的logoutTime中有May。提前感谢您的支持和指导。当我尝试回显或打印$maycount时,我只得到了0

<?php
function MayVPNCount($searchVPNArrayResults, $may){
    $may = 'may';
    $maycount = 0;

    foreach($vpnSessionArray as $oneVPNSession){
        if (strpos($oneVPNSession->logoutTime, $may) !== false)
            $maycount += 1;
        }
    return($maycount);
}
?>

也许你需要这样的东西:

function MayVPNCount($searchVPNArrayResults, $may){
    //in this case $searchVPNArrayResults is where Im going to look
    //$may is what Im looking for.

    $text = $searchVPNArrayResults;

    $stringIMlooking = $may;

    $position = 0;
    $maycount = 0;

    //stripos() intead of strpos() for case insensive
    while (($position  = strpos($text, $stringIMlooking, $position ))!== false) {    

    $position  = $position  + strlen($stringIMlooking);


    $maycount++;

    }
    return $maycount;
    }


echo MayVPNCount("the whole text one two tree for one five", "one");
您需要更改变量。如果您有一个数组,则可以使用infrade()函数获取一个字符串

正如@rickdenhaan所说,substr_count()更好:

function MayVPNCount($searchVPNArrayResults, $may){

    $text = $searchVPNArrayResults;

    $stringIMlooking = $may;

    //case sensitive
    return substr_count($text, $may) ;

     //case insensituve:
    //return substr_count(strtoupper($text),strtoupper($may));

}

$vpnSessionArray
来自哪里?你不应该在
$searchVPNArrayResults
中循环吗?在循环开始之前,你还用
“may”
覆盖了
$may
?函数本身正在按预期工作。请说明您是如何填写
$searchVPNArrayResult
的,还是其中的一个var_转储(和/或
$vpnSessionArray
-真正的var名称是什么…)。首先,前面的评论者提出了一些好问题(您确实需要解决这些问题)。除此之外,您如何调用此函数?
$searchVPNArrayResults
的内容是什么?
$may
包含什么?这里有太多的未知。请阅读:除其他澄清请求外,您还说“有4个条目的登录时间中有May”,但您要查找的是
May
,而不是
May
。这个问题中有太多的未知数,无法回答。任何答案基本上都是暗箭伤人。OP首先需要修正这个问题。OP函数背后的概念没有错,它试图找到数组中某个属性中具有特定子字符串的对象数。但是,如果要将数组中的所有项连接到一个字符串中,最好使用本机
substr\u count()
函数,而不是编写自己的循环,以获得基本相同的结果。您好@Emeeus,谢谢您的帮助。我尝试了你的代码,它给我2作为输出。它应该给我4分,但不知道我如何/为什么一直得到2分。@docwobster保持在中间,substr_计数和STRPO是这样的sensitive@Emeeus再次感谢,我现在可以用substr_count实现了!