drrog9853 2016-11-16 19:33
浏览 25
已采纳

使用变量计算数组中的值的数量

I'm trying to count the number of times a certain value turns up in an array. Except this value will always increment by 1, and there is an unknown number of these values in the array.

Example:

$first = array( 'my-value-1','my-value-2','my-value-3' );

$second = array( 'my-value-1','my-value-2','my-value-3', 'my-value-4', 'my-value-5' );

My goal is to be able to retrieve a count of 3 for $first and a count of 5 for $second in the example above.

There may be other values in the array, but the only values I'm interested in counting are the ones that start with my-value-.

I won't know the number of the values in the array, but they will always start with my-value- with a number added to the end.

Is there a way to count the number of times my-value- shows up in the array with some sort of wildcard?

  • 写回答

3条回答 默认 最新

  • duanhao9176 2016-11-16 19:37
    关注

    Use a regex to filter the array and count the values that match. You could also use ^ to force it to be at the beginning ^my-value-\d+:

    $count = count(preg_grep('/my-value-\d+/', $first));
    

    You could also do it this way. Again you could use === 0 instead to make it match at the beginning:

    $count = count(array_filter($first, function($v) {
                                            return strpos($v, 'my-value-') !== false;
                                        }));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题