This article mainly tells you how PHP disrupts associative arrays.
Recommended reference tutorial: "PHP Tutorial"
For PHP learners, when it comes to disrupting arrays, the shuffle function may be the first thing that comes to mind. But how to solve the problem of disrupting the associative array and retaining the key-value pairs may be difficult.
Below we will combine specific code examples to introduce to you how php disrupts the associative array and maintains the key-value pair.
The specific solution code example is as follows:
<?php function shuffle_assoc($my_array) { $keys = array_keys($my_array); shuffle($keys); foreach($keys as $key) { $new[$key] = $my_array[$key]; } $my_array = $new; return $my_array; } $colors = array("color1"=>"Red", "color2"=>"Green", "color3"=>"Yellow"); echo '<pre class="brush:php;toolbar:false">'; print_r(shuffle_assoc($colors));
The effect is as shown in the figure below:
As shown in the figure, every time we refresh Shuffle once, and the original key-value pairs remain unchanged.
Note:
1. array_keys() function Returns a new array containing all the key names in the array.
Syntax:
array_keys(array,value,strict)
If the second parameter is provided, only the key name with the key value is returned. If the strict parameter is specified as true, PHP will use equality comparison (===) to strictly check the data type of the key value.
2. shuffle() function Rearranges the elements in the array in random order. This function assigns new key names to elements in the array. Existing key names will be deleted.
This article is an introduction to the method of PHP disrupting associative arrays. It is also very simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to scramble associative array in php. For more information, please follow other related articles on the PHP Chinese website!