简体   繁体   中英

PHP: What's the most efficient way to summarize a large array into just 10 arrays?

My web app returns to the user all images in a specific folder (pictures taken for each day in the month) via array of filenames. Issue is that sometimes the number of images are just too many (30-500 images).

What i wanted to do is provide a summary of that array, by reducing that array to just 10 images. I could easily get the first 10 by limiting the loop. But that just represents the first part (for few images of the day) . I wanted to get 10 images from that array in a way that the 10 images is equally spread out throughout the day.

I could think of several ways to do this but involving quite a lot of code.

Was wondering if anyone knows of a cool array function or method that solves this problem?

There is no built-in function in php for do that. The best thing I think is using of sizeof() function:

$size = sizeof($array);
$chunkSize = ceil($size/10);
for($i = 0;$i<$size;$i+=$chunkSize){
    echo $array[$i];
}
$images = ... //result from database
$result = [];

$total = count($images);
$index = round($total/10);

for($i = 0; $i < $total; $i += $index) {
    $result[] = $images[$i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM