这个问题是从我之前的here问题中继续进行的。
但是,我想用最基本的术语来说明这一点,希望有人能够帮助我找到解决方法。
考虑这个多维数组:
$images = array(
0 = array(
'height' => 100
),
1 = array(
'height' => 90
),
2 = array(
'height' => 60
),
3 = array(
'height' => 30
)
);
请注意,数组已按高度降序排序!
这些图像需要被推入三列,同时尽可能地保持列的高度。因此,结果数组(上例)将如下所示:
$gallery_columns = array(
1 => array(
'height' => 100
'images' => array(
0 = array(
'height' => 100
),
)
),
2 => array(
'height' => 90
'images' => array(
0 = array(
'height' => 90
),
)
),
3 => array(
'height' => 90
'images' => array(
0 = array(
'height' => 60
),
1 = array(
'height' => 30
),
)
)
);
我正在努力编写一个算法来实现上述目标。没有使用大量嵌套循环等,任何人都能看到实现这个目标的好方法吗?
答案 0 :(得分:1)
这可能就是你要找的东西:
$images = array(
0 => array(
'height' => 100
),
1 => array(
'height' => 90
),
2 => array(
'height' => 60
),
3 => array(
'height' => 30
)
);
$gallery_columns = array(
1 => array(
'height' => 0,
'images' => array()
),
2 => array(
'height' => 0,
'images' => array()
),
3 => array(
'height' => 0,
'images' => array()
)
);
foreach ($images as $img)
{
// start with first column as the shortest
$shortest_colm = &$gallery_columns[1];
// loop over all the columns, updating the shortest column if shorter
for ($i = 2; $i <= 3; $i++)
{
if ($gallery_columns[$i]['height'] < $shortest_colm['height'])
{
$shortest_colm = &$gallery_columns[$i];
}
}
// push the image into the shortest column
$shortest_colm['height'] += $img['height'];
$shortest_colm['images'][] = $img;
}
print_r($gallery_columns);
输出:
Array
(
[1] => Array
(
[height] => 100
[images] => Array
(
[0] => Array
(
[height] => 100
)
)
)
[2] => Array
(
[height] => 90
[images] => Array
(
[0] => Array
(
[height] => 90
)
)
)
[3] => Array
(
[height] => 90
[images] => Array
(
[0] => Array
(
[height] => 60
)
[1] => Array
(
[height] => 30
)
)
)
)
<强>加成:强>
foreach($gallery_columns as &$column)
{
shuffle($column['images']);
}
由于您按照从大到小的顺序插入图像,所以插入后可以随机播放图像。这样,它不会在顶部显示所有大图像,在底部显示小图像。