Count the number of elements in a two-dimensional array

Source: Internet
Author: User

Record the solution to the next problem, which involves the usage of several functions.

Describe the problem first. 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 we need to count the number of each number, that is, the number of people who voted for each vote, and sort them.

This is my idea.

1. read data from the congtent field of the database and combine them into a string.

<? Phpwhile ($ 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.

$ 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.

$ Rs = array_count_values ($ r );

4. Sorting

Sorting is simple, but to keep the key value, you can use the built-in asort () function.

Asort ($ rs); echo '<pre>'; print_r ($ rs); echo '</pre> ';

Record several functions used.

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.