Randomly retrieve several different numbers from an array
/** This program is to randomly retrieve several different elements from an array that is not repeated * The difficulty is to prevent the number of elements that have been obtained (especially when the last element is obtained ). ), try to reduce the collision as much as possible * // first algorithm, the idea of others on CSDN/* $ num = 0; $ array = array (1, 2, 3, 4, 5, 6, 7, 8, 9); $ arr = array (); $ g = 5; $ tag = true; while ($ tag) {$ count = count ($ array); $ t = rand (0, 1); if ($ t = 1) {$ arr [] = $ array [$ num]; unset ($ array [$ num]);} $ num ++; if (count ($ arr) ==$ g) {$ tag = false;} if ($ num = $ count) {$ num = 0; // loop} var_dump ($ Rr); * // The second algorithm. // You can replace the data with the unobtained data after each fetch, and then randomly obtain the value of function swap (& $ a, & $ B) from the unobtained data) {$ temp = $ B; $ B = $ a; $ a = $ temp;} $ result = array (); $ src = array (); for ($ I = 0; $ I <40; $ I ++) {$ src [] = $ I + 1;} $ arr_len = count ($ src ); $ count = 20; $ index = 0; while ($ index <$ count) {$ random = rand (0, $ arr_len-$ index-1 ); $ result [] = $ src [$ random]; swap ($ src [$ random], $ src [$ arr_len-$ index-1]); $ index + = 1;} print_r (json_encode ($ result); print_r (json_encode ($ src ));