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条)

报告相同问题?

悬赏问题

  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信