如果重复结果,请与Foreach合作

时间:2016-03-20 20:22:23

标签: php if-statement foreach

我做了一个if来控制我的foreach的第一行但是当我执行时,echo显示3次相同的事情

    foreach ($fotoscards as $fotos) {
                $i == 1;
                if ($i == 1) {

                    echo "[{image:", $fotos , '},';
                    $i++;

                }
                else echo '{image:', $fotos , '},';
                    $i++;


            }

我得到的输出:

{image:pics/570212366814_1008100572561339_77379992_n3.jpg},
[{image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/154212308582_908192572599216_6538482440643426144_n.jpg},
 {image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/154212308582_908192572599216_6538482440643426144_n.jpg},
 {image:},
 {image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/154212308582_908192572599216_6538482440643426144_n.jpg},
 {image:},
 {image:},
 {image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/154212308582_908192572599216_6538482440643426144_n.jpg},
 {image:},
 {image:},
 {image:pics/7593uphol1.jpg},

我希望输出为:

[{image:pics/570212366814_1008100572561339_77379992_n3.jpg},
 {image:pics/655210502212_694548387334477_1457367303128125710_n.jpg},
 {image:pics/154212308582_908192572599216_6538482440643426144_n.jpg},
 {image:pics/7593uphol1.jpg},

3 个答案:

答案 0 :(得分:1)

您未在第2行将$i变量设置为1,而是将其与1进行比较。因为我认为您尚未声明或设置$i在其他任何地方,执行else语句。所以在第2行,

$i == 1;

应该是

$i = 1;

答案 1 :(得分:0)

您可以通过在foreach循环之前打印初始括号来简化代码:

        echo '[';
        foreach ($fotoscards as $fotos) {
            echo "{image:', $fotos , '},';
        }

答案 2 :(得分:0)

您的问题是您在$i循环中设置了for计数器变量 ,因此在每次迭代时它的值再次设置为1。您需要在for循环之前声明一次。

另一个问题是,else语句未包含在括号中,因此即使$i++通过,您的第二个if也会被执行。当你只想要一个时,这是$i++的两倍。

$i = 1;
foreach ($fotoscards as $fotos) {
    if ($i == 1) {
        echo "[{image:", $fotos , '},';
        $i++;
    }
    else {
        echo '{image:', $fotos , '},';
        $i++;
    }
}

如果您不想使用外部计数器,可以使用

for ($i = 0; $i < count($fotoscards); $i++) {
    if ($i == 0) {
        echo "[{image:", $fotoscards[$i], '},';
        $i++;
    }
    else {
        echo '{image:', $fotoscards[$i], '},';
        $i++;
    }
}