我想获得随机数组:
例如:
$navItems= array(
array(
slug => "top10.php",
title => "Top 10 geriausi"
),
array(
slug => "index.php",
title => "Pagrindinis"
),
array(
slug => "top-prasciausi.php",
title => "Top 10 prasciausi"
),
array(
slug => "visi-politikai.php",
title => "Visi politiki"
),
);
然后在foreach循环中使用这个随机数组,如下所示:
foreach ($navItems as $item) {
echo "<li class=\"hov\"><a href=\"$item[slug]\">$item[title]</a><li>";
}
而不是$navItems
变量我想使用$navItems
数组
答案 0 :(得分:2)
您可以使用shuffle
随机化数组
注意:如果您尝试从数组中选择一个,可以使用shuffle
并选择数组的第一个元素。
$navItems = array(
array(
'slug' => "top10.php",
'title' => "Top 10 geriausi"
),
array(
'slug' => "index.php",
'title' => "Pagrindinis"
),
array(
'slug' => "top-prasciausi.php",
'title' => "Top 10 prasciausi"
),
array(
'slug' => "visi-politikai.php",
'title' => "Visi politiki"
),
);
shuffle( $navItems );
echo "<pre>";
print_r( $navItems );
echo "</pre>";
这将导致某事,如:
Array
(
[0] => Array
(
[slug] => index.php
[title] => Pagrindinis
)
[1] => Array
(
[slug] => visi-politikai.php
[title] => Visi politiki
)
[2] => Array
(
[slug] => top10.php
[title] => Top 10 geriausi
)
[3] => Array
(
[slug] => top-prasciausi.php
[title] => Top 10 prasciausi
)
)
Doc:shuffle