【问题标题】:Inserting added logic on the fly within a PHP for loop that generates an array在生成数组的 PHP for 循环中动态插入添加的逻辑
【发布时间】:2012-03-06 18:30:07
【问题描述】:

情况: 我有一个首页滑块,用户可以在其中从选项菜单中选择他们想要包含在首页滑块中的页面。这些选项存储在一个静态数组中,并且只打印用户的选择,直到我确定的任何限制,请参见下面的代码。

<?
        // Counts the Number of Boxes available for the front page slider
        $numberOfBoxes = 6; 

        $group = array (); // Create an empty array to store all of your final data


        //Counts all the checkboxes and their corresponding sliderboxes
        for ( $a = 1; $a <= $numberOfBoxes; $a++ )
        {
            if (${'checkBox_'.$a} == TRUE){

            $tempDefaultArray = ${'sliderBox_'.$a};
            array_push($group , $tempDefaultArray); // Push the data to the $group array
            }
        }

        $arraySize = sizeof($group); // Find the size of the final array

        // Take the outcome from the above calculations and create slider
        for ( $i = 0; $i <= ($arraySize - 1); $i++ )
        {
            $image = $group[$i]['image'];
            $title = $group[$i]['title'];
            $tagline = $group[$i]['tagline'];
            $url = $group[$i]['url'];
            $vanityUrl = $group[$i]['vanityUrl'];

            print'
            <li '.$sliderDivider.'>
            <img src="'.$image.'" border="0"/>
            <h1>'.$title.'</h1>
            <p>'.$tagline.'</p>
            <a href="'.$url.'" '.$sliderLink.'/>'.$vanityUrl.'</a>
            ';}?>

问题: 这完美地工作,但我想说明,如果一个特定的外部变量 isset 和/或 true,我的滑块中的第三个框将填充来自我数组中特定对象的数据。我想保留这个现有逻辑的功能,如果设置了该变量,只需合并一些额外的内容来覆盖第三个框。

示例: 我将滑块选项选择为:文章 1、文章 2、博客 1、图像 1,然后在自定义的单独区域中,用户选择 YouTube 视频。默认情况下,当设置该变量时,我们将其称为 $youTube,然后第三个选择(在本博客 1 中)将默认为 YouTube。另外请注意,此默认框与静态选项位于同一数组中。

这是一件很难解释的事情,如果他们有任何忍者 PHP 可以推荐一种有效的方法来处理这个问题,我将不胜感激。

【问题讨论】:

    标签: php for-loop logic


    【解决方案1】:

    嗯,如果我理解你的问题,如果在数组变量之外设置了某个条件,你想在循环中进行覆盖吗?

    你可以在你的循环中放置一个 if 语句来检查外部变量:

    if($external_var=="something") {
        $image = $static_array['image'];
        $title = $static_array['title'];
        $tagline = $static_array['tagline'];
        $url = $static_array['url'];
        $vanityUrl = $static_array['vanityUrl'];
    } else {
        $image = $group[$i]['image'];
        $title = $group[$i]['title'];
        $tagline = $group[$i]['tagline'];
        $url = $group[$i]['url'];
        $vanityUrl = $group[$i]['vanityUrl'];
    }
    

    【讨论】:

    • 感谢您的输入,但我只想在第三次迭代时执行。并且不覆盖第三个,而只是将其推回第四个位置。
    • 对不起,这不是你想要的,也许看看这个帖子:php.net/manual/en/function.array-push.php#106717
    猜你喜欢
    • 2022-01-16
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多