构建PHP函数以显示多维数组中的图像库

时间:2017-07-19 05:32:14

标签: php arrays multidimensional-array

我花了很多时间试图围绕多维数组,以构建一个PHP函数,我可以调用它来填充一个可能容纳100个元素的图库。此时,一遍又一遍地复制和粘贴HTML部分会更容易,但我想知道如何使这个工作,为未来的项目。

我已经找到了关于使用多维数字阵列的foreach循环的其他问题的解决方案,但我还没有能够使它适应我的情况。在一个例子中,最接近我自己的情况,解决方案不再有效 - 但我没有让代表对此发表评论。我使用该示例中的代码作为我自己尝试的基础。我欢迎任何帮助!我的评论可能有助于解释我想要实现的目标,如果它还不清楚的话。

到目前为止,这是我的PHP代码:

<?php 
// Use PHP array to populate the image path, title (for alt tag), and longer description (for image caption)
function build_html ($imgsrc, $title, $desc) {
    echo
        '<div class="responsive">
        <div class="gallery">
            <img src="$imgsrc" alt="$title" width="300" height="200">
            <div class="desc">$desc</div>
        </div>
        </div>';
}
// List of images; filenames will be numerical, so later I may switch to using $i++ shortcut in place of imgsrc
$gallery = array (
    array (
    "imgsrc"    =>  "i/Alice0.jpg", 
    "title"     =>  "Front of House", 
    "desc"      =>  "View of the house from the front sidewalk"
    ),
    array ( 
    "imgsrc"    =>  "i/Alice1.jpg", 
    "title"     =>  "Front door", 
    "desc"      =>  "Close-up of front door"
    )
);
// This is just for debugging, to confirm that I really have a multidimensional array
print_r($gallery); 

// BROKEN: this should use foreach loop(s) to gather the elements and pass them to the build_html function defined above.  
function display_gallery () { 
    foreach ($gallery as $img) { 
        $imgsrc = $img['imgsrc'];
        $title = $img['title'];
        $desc = $img['desc'];
        build_html($imgsrc, $title, $desc);

    }
}
// Calling the function in body of page
display_gallery();
?>

编辑:我目前收到的错误消息是:

  

警告:为foreach()提供的参数无效   第121行/home/varlokkur/house.anthropo.org/index.php

编辑:如果以后有人遇到这个问题,这里是我修改后的代码,按预期工作。请注意,aendeerei提供的解决方案是一个更好的示例,但此解决方案最接近原始代码。 2个更改使其工作:

  1. 修正了built_html函数以正确使用传递的变量
  2. 修正了display_gallery函数以使用$ gallery变量
  3. 固定代码:

    <?php 
    // Use PHP array to populate the image path, title (for alt tag), and longer description (for image caption)
    function build_html ($imgsrc, $title, $desc) {
        echo
            '
            <div class="responsive">
            <div class="gallery">
                <img src="' . $imgsrc . '" alt="' . $title . '" width="300" height="200">
                <div class="desc">'. $desc . '</div>
            </div>
            </div>
            ';
    }
    
    // List of images; filenames will be numerical, so later I may switch to using $i++ shortcut in place of imgsrc
    
    $gallery = array (
        array (
        "imgsrc"    =>  "i/Alice0.JPG", 
        "title"     =>  "Front of House", 
        "desc"      =>  "View of the house from the front sidewalk"
        ),
        array ( 
        "imgsrc"    =>  "i/Alice1.JPG", 
        "title"     =>  "Front door", 
        "desc"      =>  "Close-up of front door"
        )
    );
    // This is just for debugging, to confirm that I really have a multidimensional array
    //print_r($gallery); 
    
    // BROKEN: this should use foreach loop(s) to gather the elements and pass them to the build_html function defined above.  
    function display_gallery ($gallery) { 
    //  global $gallery;
        foreach ($gallery as $img) { 
            $imgsrc = $img['imgsrc'];
            $title = $img['title'];
            $desc = $img['desc'];
            build_html($imgsrc, $title, $desc);
        //  var_dump($gallery);
        }
    }
    //var_dump($gallery);
    // Calling the function in body of page
    display_gallery($gallery);
    ?>
    

3 个答案:

答案 0 :(得分:2)

Unlike in JavaScript,PHP中没有冒泡范围。 PHP中的函数作用域与外部作用域隔离。您的$gallery是在函数范围之外定义的。在函数内部,它是未定义的。这就是为什么你得到为foreach()消息提供的无效参数的原因,因为foreach需要一个数组,但它不在那里。当您在函数中var_dump($gallery)时,您将看到它未定义。

解决方案是将$gallery传递给display_gallery(),例如

function display_gallery(array $gallery) {
   // the code as is
}
display_gallery($gallery);

另一种方法是使用the global keyword

function display_gallery() {
    global $gallery;       
    // the code as is
}
display_gallery();

然而,虽然后者看起来像一个方便而简单的修复,reaching from an inner scope to an outer scope is usually harder to maintain and more error prone in the long run。为了完整起见,我将其包括在内,但建议使用第一种方法,例如:传入变量。

答案 1 :(得分:1)

注意:

  • 我已将图片列表中的file名称分开,因此如果它将来可能会成为整数,也可以正常使用。
  • 我添加了其他信息,例如&#34; alt&#34;,&#34; width&#34;,&#34; height&#34;。 &#34; Alt和#34;手段 替代文字,显示无法显示图像时。但是&#34; title&#34; 是用于悬停工具提示的属性。
  • 我将函数名称更改为intention-revealing names。我想告诉你PHP中的函数/方法名称应该在&#34; camelCase&#34;中定义。格式(参见PHP建议PSR-1: Basic Coding Standard)。
  • 我在sprintf()中使用了函数displayImageCard(),向您展示如何实现更好的可读性以及从输出字符串中分离PHP变量。
  • 你应该&#34;注射&#34; $gallery数组作为displayImageGallery()函数的参数。缺少此函数参数是您收到的错误的来源。
祝你好运!

<?php

/*
 * -----------------
 * Gallery functions
 * -----------------
 */

/**
 * Display image card.
 * 
 * @param string $file File name.
 * @param string $extension File extension (jpg|png, etc).
 * @param string $path File path.
 * @param string $alt Alternative text.
 * @param string $title Title used in tooltips.
 * @param string $description Description.
 * @param integer $width Width.
 * @param integer $height Height.
 * @return string Output string.
 */
function displayImageCard($file, $extension, $path, $alt, $title, $description, $width = 300, $height = 200) {
    echo sprintf('<div class="responsive">
                            <div class="gallery">
                                <img src="%s" alt="%s" title="%s" width="%s" height="%s">
                                <div class="desc">%s</div>
                            </div>
                        </div>'
            , $path . $file . '.' . $extension
            , $alt
            , $title
            , $width
            , $height
            , $description
    );
}

/**
 * Display image gallery.
 * 
 * @param array $gallery [optional] Images list.
 * @return void
 */
function displayImageGallery(array $gallery = array()) {
    echo '<pre>' . print_r($gallery, true) . '</pre>';

    foreach ($gallery as $key => $image) {
        $file = $image['file'];
        $extension = $image['extension'];
        $path = $image['path'];
        $alt = $image['alt'];
        $title = $image['title'];
        $description = $image['description'];

        displayImageCard($file, $extension, $path, $alt, $title, $description);
    }
}

/*
 * ---------------
 * Display gallery
 * ---------------
 */

// Images list.
$gallery = array(
    array(
        'file' => 'i/Alice0',
        'extension' => 'jpg',
        'path' => 'abc/',
        'alt' => 'Front of House',
        'title' => 'Front of House',
        'description' => 'View of the house from the front sidewalk',
    ),
    array(
        'file' => 'i/Alice1',
        'extension' => 'jpg',
        'path' => 'def/',
        'alt' => 'Front door',
        'title' => 'Front door',
        'description' => 'Close-up of front door',
    )
);

// Display image gallery.
displayImageGallery($gallery);

答案 2 :(得分:1)

这将解决它:

function display_gallery ($gallery) {     
foreach ($gallery as $img) { 
    $imgsrc = $img['imgsrc'];
    $title = $img['title'];
    $desc = $img['desc'];
    build_html($imgsrc, $title, $desc);
}
}
// Calling the function in body of page
display_gallery($gallery);

同样,你可以把你定义数组的部分放在函数中:

function returnArray() {
    // $gallery = ...
    return ($gallery);
}

然后在foreach循环中:

foreach (returnArray() as $img) { ... }