Home > php教程 > php手册 > body text

php中数字与关联数组顺序打乱

WBOY
Release: 2016-05-25 16:56:13
Original
1036 people have browsed it
关于数组排序,PHP内置了shuffle()函数,可以重排数组排序,但是此函数“将删除原有的键名而不仅是重新排序”,如果传入的是关联数组,则关联数组的键名将丢失。

 解决方法如下:关联数组和索引数组都可以用

 代码如下 复制代码

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



永久地址:

转载随意~请带上教程地址吧^^

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template