php foreach html输出 - 新手

时间:2017-10-11 10:51:41

标签: php html foreach logic

抱歉这个非常愚蠢的问题。 它似乎比编程问题更具逻辑性问题,但无论如何。

所以我有这个很好的数组,我想用html输出,我想把它分成三个元素组。

<DIV>
   product1
   product2
   product3
</DIV>
<DIV>
  product4
</DIV>

这是我的代码

 $counter = 0;

        foreach ($prods as $prod) {
            if($counter == 0 || ($counter % 3) == 0) {
                $htm_l .= '<div data-count="' . $counter . '">';
            }

            $htm_l .= '<br> PROD' . $counter;
            $counter++;

            if($counter == 0 || ($counter % 3) == 0) {
                $htm_l .= '</div>';
            }
        }

当然它会产生错误的结果,如:

<div data-count="0">
    <br> PROD0
    <br> PROD1
    <br> PROD2
</div>
<div data-count="3">
    <br> PROD3

缺少结束div。 什么是实现我的结果的干净方法? 提前致谢

4 个答案:

答案 0 :(得分:1)

一个快速解决方案在条件之后移动$counter++;。您的完整代码将是:

 $counter = 0;
$htm_l = "";

foreach ($prods as $prod) {
    if($counter == 0 || ($counter % 3) == 0) {
        $htm_l .= '<div data-count="' . $counter . '">';
    }

    $htm_l .= '<br> PROD' . $counter;
    if($counter == 0 || ($counter % 3) == 0) {
        $htm_l .= '</div>';
    }
    $counter++;


}

echo $htm_l;

答案 1 :(得分:1)

使用以下代码

void CMyDlg::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
  CClientDC dc(this);
  CFont* pFont = GetFont();
  CFont* pFontPrev = NULL;

  if (pFont != NULL)
    pFontPrev = dc.SelectObject(pFont);

  int iborder = ::GetSystemMetrics(SM_CYBORDER);
  CSize sz = dc.GetTextExtent(_T("0"));
  lpMeasureItemStruct->itemHeight = sz.cy + 2*iborder;

  if (pFont != NULL)
    dc.SelectObject(pFontPrev);

  __super::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
}

答案 2 :(得分:0)

您可能需要查看array_chunk(),它将数组块化为具有X元素的数组:https://secure.php.net/manual/en/function.array-chunk.php

$prods = ['Product1', 'Product2', 'Product3', 'Product4'];
foreach (array_chunk($prods, 3) as $chunk) {
    echo '<div>' . PHP_EOL;
    foreach ($chunk as $product) {
        echo '<br>' . $product  . PHP_EOL;
    }
    echo '</div>'  . PHP_EOL;
}

答案 3 :(得分:0)

$counter=3之后1使用$counter++增加$counter=4所以现在 if($counter == 0 || ($counter % 3) == 0) { $htm_l .= '</div>'; }

和你的检查条件

</div>

错误且没有forloop分配,因此在$counter=0结束后您将设置if($counter == 0 || ($counter % 3) == 0) { $htm_l .= '</div>'; } ,然后检查

<?php
$counter = 0;
$htm_l="";
foreach ($prods as $prod){
    if($counter == 0 || ($counter % 3) == 0) {
        $htm_l .= '<div data-count="' . $counter . '">';
    }

    $htm_l .= '<br> PROD' . $counter;
    $counter++;

    if($counter == 0 || ($counter % 3) == 0) {
        $htm_l .= '</div>';
    }
}
$counter=0;
if($counter == 0 || ($counter % 3) == 0) {
    $htm_l .= '</div>';
}
echo $htm_l;

所以它会起作用

heat