【问题标题】:php function to search array and return countphp函数搜索数组并返回计数
【发布时间】:2018-05-11 21:29:50
【问题描述】:

我还在学习 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);
}
?>

【问题讨论】:

  • $vpnSessionArray 来自哪里?你不应该循环使用$searchVPNArrayResults 吗?
  • 你还在循环开始之前用"may" 覆盖$may...?
  • 函数本身按预期工作。请显示您如何填写 $searchVPNArrayResult 或其中的 var_dump(和/或 $vpnSessionArray- 真正的 var 名称是什么......)。
  • 首先,之前的评论者提出了很好的问题(您确实需要解决这些问题)。不仅如此,你是如何调用这个函数的? $searchVPNArrayResults 的内容是什么? $may 包含什么?这里有太多的未知数。请阅读:How to create a Minimal, Complete, and Verifiable example 和 How do I ask a good question?
  • 除了其他澄清请求外,您说“有 4 个条目的 logoutTime 和 May 在其中”,但您正在寻找 may,而不是 May。

标签: php


【解决方案1】:

也许你需要这样的东西:

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");

您需要更改变量。如果你有一个数组,你可以使用 implode() 函数来获取一个字符串。

正如@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));

}

【讨论】:

  • 这个问题有太多未知数,无法回答。任何答案基本上都是在黑暗中刺伤。 OP需要先修改问题。
  • OP 函数背后的概念没有错,它试图在数组中查找在其属性之一中具有特定子字符串的对象的数量。但是,如果您要将数组中的所有条目连接成一个字符串,则最好使用本机 substr_count() 函数,而不是编写自己的循环来获得基本相同的结果。
  • 嗨@Emeeus,感谢您的帮助。我试过你的代码,它给了我 2 作为输出。它应该给我 4,但不明白我如何/为什么一直得到 2。
  • @docwobster 在中间保持 substr_count 和 strpos 区分大小写
  • @Emeeus 再次感谢,我现在可以使用 substr_count 了!
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2018-03-14
  • 2014-04-16
  • 2017-11-16
相关资源
最近更新 更多