【问题标题】:Different markup based on foreach output基于 foreach 输出的不同标记
【发布时间】:2016-08-28 12:56:24
【问题描述】:

这几天我一直在尝试解决这个问题,但不幸的是,到目前为止还没有运气。我想根据类别/类型对约会进行排序并将它们放在单独的 div 中。例如:

我的 foreach 循环为“normal”和“special”类型的每个可用约会生成一个输入复选框。

现在我可以获得所有约会的列表:

print $apptOutput;

这会输出用户可以使用复选框选择的约会列表:

  • 30-08-16 11:05 特别
  • 31-08-16 09:55 特别
  • 31-08-16 20:05 正常
  • 01-09-16 20:00 正常
  • 02-09-16 20:05 正常

我想要做的是给每个类别一个不同的 div,这样输出是分开的。例如,我希望它是这样的:

<div id="normal">
  <label for="normal">Normal</label>
    <?php print $apptOutput; ?>
</div>

特别版:

<div id="special">
  <label for="special">Special</label>
     <?php print $apptOutput; ?>
 </div>

【问题讨论】:

    标签: php foreach checkboxlist


    【解决方案1】:

    如果已经生成了 HTML,那么在您拥有 $appOutput 的阶段就无法轻松解决问题。您需要在生成$appOutput 时解决它,因为这样更容易识别哪些是特殊,哪些是正常

    假设您从数据库中获取此数据。在您从数据库中遍历结果集时,您可以根据 SpecialNormal 的标准将每个项目放在不同的数组键中,使其更容易将每种类型的项目的输出生成到自己的 div 中。

    $data = [
        "Special" => [],
        "Normal"  => [],
    ];
    // $resultSet being your database result set or however you get the data
    foreach($resulSet as $result) {
        if ($result["type"] == "Special") {
            $data["Normal"][] = $result;
        } elseif ($result["type"] == "Normal") {
            $data["Special"][] = $result;
        }
    }
    

    现在在您的模板中,您可以更轻松地生成结果。

    <div id="normal">
        <?php foreach($data["Nomral"] as $item) { ?>
            <label for="normal"><?=$item['name']?></label>
            <input type="checkbox" ...>
        <?php } ?>
    </div>
    
    <div id="special">
        <?php foreach($data["Special"] as $item) { ?>
            <label for="normal"><?=$item['name']?></label>
            <input type="checkbox" ...>
        <?php } ?>
    </div>
    

    【讨论】:

    • 这非常有效。虽然,在我的模板文件中甚至不需要 foreach。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    相关资源
    最近更新 更多