【问题标题】:PHP: Create arrays from a function call inside a foreach loop and merge themPHP:从 foreach 循环内的函数调用创建数组并将它们合并
【发布时间】:2021-01-28 20:49:32
【问题描述】:

此代码的目的是识别调用代码的文件夹中的所有图像文件,以创建图像库。图片按字母数字顺序列出,但我需要特定的顺序,因此使用标准 PHP 数组排序函数重新排序不能满足我的需求。

我正在使用 if 语句将图像集合放入不同的数组中,然后将数组合并到我需要的顺序中。

当我将代码作为 foreach 循环的一部分运行时,它运行良好。我想将 if 条件放入函数中以重用代码,但是当我将代码复制并粘贴到函数中时,我只是得到一个空白页:

// echo statements are just for testing.

foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
    $img_src03 = basename($var03);
    $img_label03 = pathinfo($var03, PATHINFO_FILENAME);

    // Assign specific values to the arrays as you cycle through $img_src03 values:
    if (substr($img_src03, 0, 5) == 'ext_f'){
        if (!isset($array33)) {
            $array33 = array();
        }
        $array33[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 5) == 'ext_r'){
        if (!isset($array33)) {
            $array33 = array();
        }
        $array33[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 6) == 'ext_po'){
        if (!isset($array34)) {
            $array34 = array();
        }
        $array34[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 3) == 'bed'){
        if (!isset($array35)) {
            $array35 = array();
        }
        $array35[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 3) == 'bth'){
        if (!isset($array36)) {
            $array36 = array();
        }
        $array36[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    }
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal);     echo '</pre><br>';

如果将完全相同的 if 条件放在位于 foreach 循环外部的函数 findImage03($img_src03, $img_label03) 中,然后从 foreach 循环内部调用,代码将无法工作。

foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
    $img_src03 = basename($var03);
    $img_label03 = pathinfo($var03, PATHINFO_FILENAME);

    // Trying to use a function call to run the if conditional. Function is outside the foreach loop. Nothing returned.
    findImage03($img_src03, $img_label03);
}

function findImage03($img_src03, $img_label03){
    // Assign specific values to the arrays as you cycle through $img_src03 values:
    if (substr($img_src03, 0, 5) == 'ext_f'){
        if (!isset($array33)) {
            $array33 = array();
        }
        $array33[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 5) == 'ext_r'){
        if (!isset($array33)) {
            $array33 = array();
        }
        $array33[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 6) == 'ext_po'){
        if (!isset($array34)) {
            $array34 = array();
        }
        $array34[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 3) == 'bed'){
        if (!isset($array35)) {
            $array35 = array();
        }
        $array35[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    } elseif (substr($img_src03, 0, 3) == 'bth'){
        if (!isset($array36)) {
            $array36 = array();
        }
        $array36[] = $img_src03;
        echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
    }
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal);     echo '</pre><br>';

【问题讨论】:

    标签: php arrays if-statement foreach


    【解决方案1】:

    在研究这个问题时,我想我发现了几个问题,所以我不确定这是否归结为不是程序员。

    1. 我找到了一个在函数() 中运行foreach() 的解决方案,而不是在foreach() 中运行函数()。 然后使用函数调用的结果创建新数组。
    2. array_merge() 仅在所有被合并的数组都保存值时才有效,否则它会失败。不确定是否可以使用 !isset 解决。

    所以这是在 function() 中运行 foreach() 的代码,它可以位于包含的文件中以提高重用效率以及维护/更新的单个源:

    // Define the function to get all the images in the current folder:
    function getImages(){
        foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var){
            $img_src = basename($var);
            
            // Assign specific values to the array as you cycle through the collection. Order here will not affect final array order.
            if (substr($img_src, 0, 5) == 'bed_1'){
                if (!isset($arrayBed_1)) {
                    $arrayBed_1 = array();
                }
                $arrayBed_1[] = $img_src;
            } elseif (substr($img_src, 0, 5) == 'bed_2'){
                if (!isset($arrayBed_2)) {
                    $arrayBed_2 = array();
                }
                $arrayBed_2[] = $img_src;
            } elseif (substr($img_src, 0, 5) == 'bed_3'){
                if (!isset($arrayBed_3)) {
                    $arrayBed_3 = array();
                }
                $arrayBed_3[] = $img_src;
            // continue for each type required.
            }           }
        } //End of foreach().
        
        // Create the pre final array for other arrays to push to which defines the sort order:
        $arrayPreFinal = array();
        
        if (isset($arrayExt_f)){                        // ext_f = exterior front
            foreach ($arrayExt_f as $val){
                array_push($arrayPreFinal, $val);
            }
        }
        if (isset($arrayExt_r)){                        // ext_r = exterior rear
            foreach ($arrayExt_r as $val){
                array_push($arrayPreFinal, $val);
            }
        }
        if (isset($arrayBed_1)){                        // bed_1 = bedroom 1
            foreach ($arrayBed_1 as $val){
                array_push($arrayPreFinal, $val);
            }
        }
        if (isset($arrayBed_2)){                        // bed_2 = bedroom 2
            foreach ($arrayBed_2 as $val){
                array_push($arrayPreFinal, $val);
            }
        }
        // continue for as many variances as require.
        
        
        return $arrayPreFinal;
    } // End of function()
    

    代码从图片所在的文件夹运行:

    // Set $iwd Image Working Directory:
    // Required before gallery_ctrl_body.php inlcude as $iwd is needed before include.
    
    // class IWD changes outside the class.
    class IWD {
        // Properties
        public $iwd;
    }
    $var = new IWD();
    $var->name = getcwd();
    $iwd = $var->name;
    
    // Script include needs to be run before function pid_text().
    include_once ('../gallery_ctrl_body.php');
    
    # Function to identify the property sub-division from directory path characters using preg_match()
    # and define a Property ID Text:
    function pid_text($sub_div) {       //Need parameter/s in function():
        $sub_div_abb = sub_div_abb($sub_div); //20200220 code
        $psc = 'ORL'; // Start of Property System Code.
        $str = getcwd();
    
        if(preg_match("/{$sub_div}/i", $str)) {
            $psc = $psc . $sub_div_abb . strtoupper(basename(__DIR__)); //sub_div_abb may already defined in UPPERCASE.
            $pid_textname = constant("PROPERTY_TEXT") . $psc; //strtoupper($psc);
        }
        return $pid_textname;                   //Return value AFTER IF statement. REQUIRED!
    }   
    $pid_text = pid_text($sub_div = 'test_200828');
        
    // Define the imagepath and variables:
    define('IMAGEPATH', dirname(__FILE__).'/'); // '/' is required.
    $img_height = 'height: 400px'; // default image height for gallery.
    $img_width = 'width: 600px'; // default image width for gallery.
    $img_counter = 0;
    $img_style = 'style="' .  $img_width . '"'; // only needs to be set once here.
    $img_total = 0;
    
    // Create the final array with function call to get images:
    $arrayFinal = getImages();
    
    // Calculate total number of images before displaying <div>
    // If calculated inside a foreach() $img_counter always equals $img_total.
    $img_total = count($arrayFinal);
    
    echo '<div class="property_text-container">';
        echo 'Gallery for ' . $pid_text;
    echo '</div>';
    
    //<!-- Slideshow container -->
    echo '<div class="slideshow-container">';
    
    // foreach ($array1 as $value){
    foreach ($arrayFinal as $value){
        $img_counter ++; // Set before function() when using function call.
        // Call the function located in gallery_ctrl_body:
        createGallery($img_width, $img_style, $filename, $img_name, $img_src, $img_counter, $img_total, $value, $pid_text);
    }
    
    // <!-- Next and previous buttons -->
    echo '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>';
    echo '<a class="next" onclick="plusSlides(1)">&#10095;</a> ';
    
    echo '</div>';
    // <!-- END: div class="slideshow-container"-->
    echo '<br>';
    
    // <!-- Dot container -->
    echo '<div class="dot-container">';
        // <!-- The dots/circles -->
        echo '<div style="text-align:center">';
            $slide_counter = 0;
            while ($slide_counter < $img_total) {
                $slide_counter ++;
                echo '<span class="dot" onclick="currentSlide(' . $slide_counter . ')"></span>&nbsp;';
            }
        echo '</div>';
    echo '</div>';
    
    // Script include needs to be run at end of page including it.
    include_once ('../gallery_ctrl_script.php');
    

    所以,这段代码有效,但我不确定它是否是正确的方法或方法。如果对我有用,因为我有一套图像命名约定,并且我的画廊可以从单个源文件控制。它适用于调用函数的文件夹中的任意数量的图像(如果存在),尽管我的属性通常少于 50 个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2023-03-24
      • 1970-01-01
      • 2016-02-09
      • 2013-11-07
      相关资源
      最近更新 更多