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

PHP函数shuffle()实现重新排序

WBOY
Release: 2016-06-13 11:10:21
Original
1084 people have browsed it

shuffle -- 将数组打乱:
bool shuffle ( array &array )

PHP函数shuffle()打乱(随机排列单元的顺序)一个数组。

注意: PHP函数shuffle()为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。

例子:

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> ?php  </span></span></span></li>
<li>
<span>$</span><span class="attribute">a</span><span> = </span><span class="attribute-value">array</span><span>(  </span>
</li>
<li class="alt">
<span>'1' =</span><span class="tag">></span><span> 'Xiao',  </span>
</li>
<li>
<span>'2' =</span><span class="tag">></span><span> 'Da',  </span>
</li>
<li class="alt">
<span>'3' =</span><span class="tag">></span><span> 'Zuo',  </span>
</li>
<li>
<span>'4' =</span><span class="tag">></span><span> 'You'  </span>
</li>
<li class="alt"><span>);  </span></li>
<li>
<span>echo "原来的数组:"."</span><span class="tag"><span> </span><span class="tag-name">br</span><span> </span><span class="tag">/></span><span>";  </span></span>
</li>
<li class="alt"><span>print_r($a);  </span></li>
<li><span>shuffle($a);  </span></li>
<li class="alt">
<span>echo "</span><span class="tag"><span> </span><span class="tag-name">br</span><span> </span><span class="tag">/></span><span>"."现在的数组:"."</span><span class="tag"><span> </span><span class="tag-name">br</span><span> </span><span class="tag">/></span><span>";  </span></span></span>
</li>
<li><span>print_r($a);  </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

看看PHP函数shuffle()的运行结果:

原来的数组:

Array ( [1] => Xiao [2] => Da [3] => Zuo [4] => You )

现在的数组:

Array ( [0] => Da [1] => Xiao [2] => You [3] => Zuo )

当然,每刷新一遍页面,"现在的数组"中的元素顺序就会改变一次。注意数组的键名发生了改变。


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