phparraysrandomlimitresultset

Pad a randomized result set array upto the prescribed LIMIT with random row data


$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++;
}

if the database return less than 6 data, I want to repeat the data in the response array. Suppose it returns 5 data, then I want to return the response array with the 5 data and one again selected randomly from that 5 data, that is returned from the database. Basically the respose will be with 6 data all total. How can I do that?


Solution

  • Try this:

    $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);