Load Array via nested foreach loops in PHP?

余生颓废 提交于 2020-01-06 14:05:58

问题


I am trying to generate an array that looks like this:

Array
(
  [Album1] => '<img src="album1_thumb1.jpg">'
  [Album1] => '<img src="album1_thumb2.jpg">'

  [Album2] => '<img src="album2_thumb1.jpg">'
  [Album2] => '<img src="album2_thumb2.jpg">'
)

Right now I have two nested foreach loops that look like so:

$subfolders = glob($directory);
foreach($subfolders as $subfolder) {
    $photos = glob($subfolder.'/*.[Jj][Pp][Gg]');
    foreach($photos as $photo) {
        $thumbnail = $subfolder.'/thumbs/'.$photoname[0].'_thumb.jpg';
        $thumb = '<img src="'.$thumbnail.'" class="thumb_image">';
        $folderthumbs[$subfolder] .= $thumb;
    }
}

This doesn't do exactly what I want, though, as it basically creates an array that looks like this:

Array
(
  [Album1] => '<img src="album1_thumb1.jpg"><img src="album1_thumb2.jpg">'

  [Album2] => '<img src="album2_thumb1.jpg"><img src="album2_thumb2.jpg">'
)

How can I correct this?

Ultimately, what I would like to do is to have one single random thumbnail from each album echoed further down the page... If someone could elaborate as well on how to do that I'd be grateful, though if I can get the Array working how I'd like then I can probably figure out how to do that (I know I need to use array_rand()).

Thanks!


回答1:


An array in PHP is really a mapping between a key and a value. The key has to be unique. Therefore you cannot have

  [Album1] => '<img src="album1_thumb1.jpg">'
  [Album1] => '<img src="album1_thumb2.jpg">'

You need to think of another data structure to meet you needs



来源:https://stackoverflow.com/questions/19873869/load-array-via-nested-foreach-loops-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!