Php 从可能的Y轴中随机显示X个div

Php 从可能的Y轴中随机显示X个div,php,javascript,html,random,Php,Javascript,Html,Random,我如何在可能总共10个div中随机显示3个div 这就是我迄今为止所尝试的: HTML: 我更喜欢PHP解决方案,尽管在这一阶段做任何事情都是有益的。基于这个问题的答案:,下面是如何在一个数组中选择n个唯一的成员: // removes n random elements from array this // and returns them Array.prototype.pick = function(n) { if(!n || !this.length) return [];

我如何在可能总共10个div中随机显示3个div

这就是我迄今为止所尝试的:

HTML:


我更喜欢PHP解决方案,尽管在这一阶段做任何事情都是有益的。

基于这个问题的答案:,下面是如何在一个数组中选择n个唯一的成员:

// removes n random elements from array this
// and returns them
Array.prototype.pick = function(n) {
    if(!n || !this.length) return [];
    var i = Math.floor(this.length*Math.random());
    return this.splice(i,1).concat(this.pick(n-1));
}
因此,您可以应用它从集合中选择3个div并显示它们:

 // build the collection of divs with your framework of choice
 // jQuery would be $('div'), Mootools/Prototype $$('div')
var divs = document.getElementsByTagName('div');
// then pick 3 unique random divs and display them
// each is part of ECMAscript5 and a number of current js frameworks
divs.pick(3).each(function (div) {
  div.style.display = "block";
});
// Prototype shortcut is divs.pick(3).invoke('show'); 

如果您正在寻找一种PHP方法,那么可以尝试这样做,假设$div是一个包含6个元素的数组

for($i = 1; $i <= 3; $i++) {
    $div_num = mt_rand(1,6);
    echo $div[$div_num];
}

对于($i=1;$i您可以在一个数组中包含可能的div内容,比如,
$divs
,然后选择如下三个:

$divs = array("Content 1", "Content 2", "Content 3"); for($i = 1; $i <= 3; $i++) { shuffle($divs); $pick = array_pop($divs); echo "<div>$pick</div>"; } $divs=数组(“内容1”、“内容2”、“内容3”);
例如($i=1;$i您还没有……?您发布的代码?…每个div中显示的数据来自何处?您是从执行SQL查询中获得的10行吗?没有数据库。为了示例,唯一的内容是“content x”。目前粘贴的代码不起作用,有什么建议吗?javascript通常不喜欢ID的数字,使用字符串。(有些客户端不喜欢字符串以数字开头。)@kennebec你建议我怎么称呼DIV?LOL-我看到了这个问题的标题,认为它与我们上周帮助解决的问题类似。打开问题,发现回答这个问题的人是同一个人。:-)必须回应随机性的呼唤;-)在这个过程中,我展示了扩展内置原型的有用性;)
for($i = 1; $i <= 3; $i++) {
    $div_num = mt_rand(1,6);
    echo $div[$div_num];
}
$divs = array("Content 1", "Content 2", "Content 3"); for($i = 1; $i <= 3; $i++) { shuffle($divs); $pick = array_pop($divs); echo "<div>$pick</div>"; }