PHP quickly get random decimal groups in large arrays

Source: Internet
Author: User

There is a guess user like the function, the user can click to change a group, to refresh the recommended content.

First through the database query, get the first 1000 data, and then randomly remove 4.

After the program has been written, found that the operation is very slow, each refresh, it will take a long time to come out.

The code is as follows:

$arr = Range (1, 100000), $start = time (), for ($i = 0; $i <, $i + +) {$key = Mt_rand (0, 99999-$i); $result [] = $arr [$ke Y];unset ($arr [$key]); sort ($arr);} $end = time (), Echo $end-$start;

The above notation, after using unset, must be sorted.

Unset only deletes the key value, and key is preserved.

After the improvement, the following wording:

$arr = Range (1, 100000), $start = time (), for ($i = 0; $i <, $i + +) {$key = Mt_rand (0, 99999-$i); $result [] = array_s Plice ($arr, $key, 1);} $end = time (), Echo $end-$start;

3-4 times more efficient.

PHP quickly get random decimal groups in large arrays

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.