PHP implements the method of counting the number of occurrences of a number in the sorting array, php Array
This example describes how to calculate the number of occurrences of a number in the sorting array in PHP. We will share this with you for your reference. The details are as follows:
Question
Count the number of times a number appears in the SORT array.
Question
Since it is a Sort array, binary search is the most efficient. Find and expand to both sides.
Code
<? Phpfunction GetNumberOfK ($ data, $ k) {if (count ($ data) = 0) {return 0 ;}$ index = 0; $ low = 0; $ high = count ($ data)-1; $ middle = 0; // The index of k is found in the binary search. while ($ low <= $ high) {$ middle = ($ high + $ low)> 1; if ($ data [$ middle] ==$ k) {$ index = $ middle; break ;} else if ($ data [$ middle]> $ k) {$ high = $ middle-1;} else {$ low = $ middle + 1 ;} $ index =-1;} // console. log (index); // if not found, if ($ index =-1) {return 0 ;}// you find the boundary for searching both the left and right sides $ start = $ index; $ end = $ index; $ count = 0; while ($ data [$ start] = $ k) {$ count ++; $ start --;} while ($ data [$ end] === k) {$ count ++; $ end ++;} return $ count-1 ;}
PS: here we recommend two statistical tools with similar functions (JS implementation) for your reference:
Online word count statistics tools:
Http://tools.jb51.net/code/zishutongji
Online character statistics and editing tools:
Http://tools.jb51.net/code/char_tongji