重复随机数组元素

时间:2016-12-19 10:22:02

标签: php

$sql = "SELECT * from banner ORDER BY RAND() limit 6";
$x=1;

while($result =mysql_fetch_assoc($banner_arr))
{
    //print_r($result);
    $response["banner_image_".$x] = //something
    $x++;
}

如果数据库返回少于6个数据,我想重复响应数组中的数据。假设它返回5个数据,那么我想返回带有5个数据的响应数组,并且从数据库返回的5个数据中再次选择一个数据。基本上,respose将总共有6个数据。我将如何做到这一点?

1 个答案:

答案 0 :(得分:1)

试试这个:

$DESIRED_SIZE = 6;
$sql = "SELECT * FROM banner ORDER BY RAND() LIMIT $DESIRED_SIZE";

// TODO read from db, store into $rows array

$rows = [["1", "banner1"], ["2", "banner2"], ["3", "banner3"], ["4", "banner4"]];
$banners = [];
while (count($banners) < $DESIRED_SIZE) {
    $banners = array_merge($banners, $rows);
}
shuffle($banners);
$result = array_slice($banners, 0, $DESIRED_SIZE);