Home > Backend Development > PHP Tutorial > The order of numbers and associative arrays in php is disrupted_PHP tutorial

The order of numbers and associative arrays in php is disrupted_PHP tutorial

WBOY
Release: 2016-07-13 16:55:45
Original
1008 people have browsed it

Regarding array sorting, PHP has a built-in shuffle() function, which can rearrange the array sorting, but this function "will delete the original key names instead of just reordering". If an associative array is passed in, then the associative array The key name will be lost.

The solution is as follows: both associative arrays and index arrays can be used

The code is as follows
 代码如下 复制代码

function array_shuffle($array)
{
    //不是数组
    if(!is_array($array)) {
        return array();
    }
    //如果为空或者只有1项
    if(($count=count($array))<=1){
        return $array;
    }
    
    //得到打乱的键
    $rand_keys = array_rand($array, count($array));
    $newArr=array();
    foreach($rand_keys as $v) {
        $newArr[$v] = $array[$v];
    }
    return $newArr;
}

Copy code
function array_shuffle($array)
{
//Not an array
If(!is_array($array)) {
         return array();
}
//If it is empty or there is only 1 item
If(($count=count($array))<=1){
          return $array;
}
         
//Get the scrambled key
$rand_keys = array_rand($array, count($array));
$newArr=array();
foreach($rand_keys as $v) {
         $newArr[$v] = $array[$v];
}
Return $newArr;
}

http://www.bkjia.com/PHPjc/631666.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/631666.html
TechArticle
Regarding array sorting, PHP has a built-in shuffle() function that can rearrange the array sorting, but this function "will delete The original key name instead of just reordering", if an associative array is passed in,...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template