"Translate" faster way to implement PHP array to weight
Original: Faster alternative to PHP ' s Array Unique Function
Overview
Functions that use PHP array_unique()
allow you to pass an array and then remove the duplicate values, returning an array with unique values. This function works very well in most cases. However, if you try to use a function in a large array array_unique()
, it will run slowly.
There is a better and faster function array_flip()
to replace the use array_unique()
of a function to create a unique array. This magical function swaps the keys and values of each element in the array, because the key values must be unique, so you get array_unique()
the same result as the function.
Faster way to implement PHP array de-weight
/* Create an array of four elements with duplicate values */$array = array (' green ', ' blue ', ' orange ', ' blue ');/* Flip an array, you will get an array of unique key values (' green ' = >0, ' Blue ' =>1, ' orange ' =>2); */$array = Array_flip ($array);/* Then flip it again, reposition the keys and values, and get the array: Array (0=> ' green ',1=> ' blue ',2=> ' orange '); */$array = Array_flip ($array);
Because we have removed some elements, the array does not appear to be a normal sequence. For example we may get: array(0=>’A’,2=>’B’,5=>’C’);
. In some cases, this is not a problem, but if you need the array's key values to keep the sequence of numbers, you can use one or two methods to solve the problem of key-value disorder.
Keys for repairing arrays using Array_merge
After adding Array_flip functions, the key values of the array will be sorted and restored to the normal sequence, such as: 0,1,2,3 ...
$array = Array (' green ', ' blue ', ' orange ', ' Blue '), $array = Array_flip ($array); $array = Array_flip ($array);/* Use Array_ The merge () function fixes the key value */$array = Array_merge ($array);
The second way, use Array_keys
Note that this method of repairing array key values is a little faster than using array_merge()
functions. You can also use the function in conjunction with the last step array_keys()
(This function returns the value after the rollover). Then when you flip the values of the array, the key values are created in order.
$array = Array (' green ', ' blue ', ' orange ', ' Blue '), $array = Array_flip ($array);/* As in the first example, but now let's extract the array's key value */$array = array _keys ($array);
Conclusion
Very simple, there is an effective performance boost compared to using the Array_unique function in a large array.