无法创建for循环数组php

时间:2012-07-12 09:56:19

标签: php arrays

<ul class="selectplanparagraph">
<li>
    <h3><?php echo $comparetxt[0][0]; ?></h3>
    <img width="280" height="80" src="<?php echo $comparetxt[0][1]; ?>" alt="">
    <p><?php echo $comparetxt[0][2]; ?></p>
</li>
<li>
    <h3><?php echo $comparetxt[1][0]; ?></h3>
    <img width="280" height="80" src="<?php echo $comparetxt[1][1]; ?>" alt="">
    <p><?php echo $comparetxt[1][2]; ?></p>
</li>
<li>
    <h3><?php echo $comparetxt[2][0]; ?></h3>
    <img width="280" height="80" src="<?php echo $comparetxt[2][1]; ?>" alt="">
    <p><?php echo $comparetxt[2][2]; ?></p>
</li>
<!-- End .selectplanparagraph --></ul>

我想循环这个而不是在阵列中有3个具有硬编码位置的LI,我宁愿做一个简单的循环。我试过但我失败了。这个循环与数组比我想象的更复杂:)至少对我来说初学者:)

数组看起来像这样:

$comparetxt = [ 
    [ "Title 1", "url 1", "text 1" ],
    [ "Title 2", "url 2", "text 2" ],
    [ "Title 3", "url 3", "text 3" ]
];

3 个答案:

答案 0 :(得分:1)

试试这个

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

答案 1 :(得分:1)

首先,您的数组符号似乎是错误的。试试这个

<?php
$comparetxt = array(
    array('title' => 'Title 1', 'url' => 'www.google.com', 'text' => 'text 1'),
    array('title' => 'Title 2', 'url' => 'www.google.com', 'text' => 'text 2'),
    array('title' => 'Title 3', 'url' => 'www.google.com', 'text' => 'text 3')
);
?>
<ul class="selectplanparagraph">
<?php foreach($comparetxt as $compare) { ?>
<li>
<h3><?php echo $compare['title']; ?></h3>
<img width="280" height="80" src="<?php echo $compare['url']; ?>" alt="">
<p><?php echo $compare['text']; ?></p>
</li>
<?php } ?>
</ul>

答案 2 :(得分:0)

这就是你要追求的吗?

foreach($comparetxt as $compareitem) {
    ?>
    <li>
    <h3><?php echo $compareitem[0]; ?></h3>
    <img width="280" height="80" src="<?php echo $compareitem[1]; ?>" alt="">
    <p><?php echo $compareitem[2]; ?></p>
    </li>
    <?php
}