The method to randomly extract some elements is simple. you only need to use array_rand and range to implement this function. if you just extract an element, you can directly use mt_rand and then grow into a random number.
The method to randomly extract some elements is simple. you only need to use array_rand and range to implement this function. if you just extract an element, you can directly use mt_rand and then grow into a random number with a length not greater than the array length.
Below I will provide you with several methods for your reference.
Method -:
The instance code is as follows:
- $ Arr = range (1, 10, 1 );
- $ Newarr = array_rand ($ arr, 6); // Obtain the keys in the six arrays at random.
- $ NewArr = array_flip ($ newarr); // key-value interchange
- $ Arr3 = array_diff_key ($ arr, $ newArr); // obtain the same key
- $ Arr1 = array_diff_key ($ arr, $ arr3); // obtain the same key
- Print_r ($ arr1 );
Result: array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [5] => 6 [9] => 10)
Method 2:
The instance code is as follows:
- $ Arr = range (1, 10, 1 );
- $ Newarr = array_rand ($ arr, 6); // Obtain the keys in the six arrays at random.
- $ ArrNew = array ();
- Foreach ($ newarr as $ k => $ v)
- {
- $ ArrNew [$ v] = $ arr [$ v];
- }
- Print_r ($ ArrNew );
Result: array ([1] => 2 [2] => 3 [3] => 4 [4] => 5 [6] => 7 [7] => 8)
Method 3: This method does not retain the key name for your reference.
The instance code is as follows:
- $ Arr = range (1, 10, 1 );
- Shuffle ($ arr); // disrupt the array
- $ Newarr = array_splice ($ arr, 0, 6 );
- Print_r ($ newarr );
Result: array ([0] => 7 [1] => 4 [2] => 2 [3] => 10 [4] => 9 [5] => 6)