PHP method for counting the number of two-dimensional array elements

Source: Internet
Author: User
The field content in the data table stores a comma-separated string with a maximum of 20 numbers and a maximum of 40. For example, a sequence of numbers such as 3, 24, 3, and 40. It is actually a field that stores multiple voting results. Now you need to count the number of each number, that is Solution
1. read data from the congtent field of the database and combine them into a string.
The code is as follows:
While ($ myrow = $ connector-> fetch_array ($ result ))
{
// $ R [] = explode (",", $ myrow ["content"]);
$ Str. = $ myrow ["content"]. ',';
}

$ Arr_str = substr ($ str, 0,-1 );
?>

Because the last number is followed by a comma, you must intercept the string.
2. split the string into arrays by commas.
The code is as follows:
$ R = explode (",", $ arr_str );

3. use array_count_values () to calculate the number of elements in a one-dimensional array.
Because array_count_values () does not seem to be able to directly count the number of elements in a two-dimensional array, we have performed the preceding two steps to obtain a one-dimensional array.
The array_count_values () function is used to count the number of occurrences of all values in the array. Returns an array. The key name of the element is the value of the original array, and the key value is the number of times this value appears in the original array.
The code is as follows:
$ Rs = array_count_values ($ r );

4. sorting
The code is as follows:
Asort ($ rs );
Echo'
';
Print_r ($ rs );
Echo'
';

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.