php script that populates photos to a html div

前端 未结 2 1541
猫巷女王i
猫巷女王i 2021-01-22 21:29

I currently have a picture page with about 250 jpeg. Images and I currently have a web page where I manually assigned a picture to a section on the page, however this is very ti

2条回答
  •  时光取名叫无心
    2021-01-22 22:24

    Your best bet is to go through the whole folder and filter the pictures accordingly like so:

    $myPicFolder = "path/to/pictures/";
    $thePics = array();
    if (is_dir($myPicFolder)) {
        if ($dh = opendir($myPicFolder)) {
            while (($file = readdir($dh)) !== false)) {
                if(!is_dir($myPicFolder . $file){
                    list($intersectionID,$section,$imgID) = explode('_'.$file);//Seperates the parts of the name for easier access
                    //check if the ID is already a key in $thePics
                    if(!array_key_exists($intersectionID,$thePics)){
                        //Add the new ID if it does not exist with an empty array.
                        $thePics[$intersectionID]=array();
                    }
                    if(!array_key_exists($section,$thePics[$intersectionID])){
                        //Add the new ID if it does not exist with an empty array.
                        $thePics[$intersectionID][$section]=array();
                    }
                    // Add a new part to the ID since each picture ID has 4 pictures.
                    $thePics[$intersectionID][$section][] = $file;
                }
            }
            closedir($dh);
        }
    }
    
    
    //$thePics will then look like:
    // array('1234'=>array(
    //        '1'=>'1234_1_01.jpeg',
    //        '2'=>'1234_2_03.jpeg',
    //        '3'=>'1234_3_02.jpeg',
    //        '4'=>'1234_4_01.jpeg'),
    //    '345422'=>array(
    //        '1'=>'345422_1_01.jpeg',
    //        '2'=>'345422_2_02.jpeg')
    //    );
    
    //Cycle through the pictures...
    foreach($thePics as $pictureID=>$quad){
        echo '
    '; foreach($quad as $quadPart=>$pictures){ echo '
    '; foreach($pictures as $pictureSRC){ echo ''; } echo '
    '; } echo '
    '; }

    Please remember to do some more verifications on the file natures to make sure you are only sending pictures... Maybe test on file extension and mime type...

    EDIT: Added some comments and used list() to give explicit names to the variables I am using for better understanding.

提交回复
热议问题