如何使用HEREDOC

时间:2017-01-07 19:17:01

标签: php twitter-bootstrap

我正在尝试遍历产品并在两个引导列中显示它们。显然,我现在拥有它的方式不会像输出那样起作用:

    Apple           Apple
    Banana          Banana
    Grapes          Grapes
    Strawberry      Strawberry

它应该看起来像:

Apple           Banana
Grapes          Strawberry


function bootloop($link) {

    $stmt = $link->prepare("SELECT `prod_name` FROM `products`");
    $stmt->execute();
    $result = $stmt->get_result();
    if($result) {
        while($row = $result->fetch_assoc()) {
            $prod_name = sanitize($row['prod_name']);

            $bootloop = <<<LOOPCOLUMNS

            <div class="col-md-6 text-center">{$prod_name}</div>
            <div class="col-md-6 text-center">{$prod_name}</div>

LOOPCOLUMNS;
            echo $bootloop;
        }
    }

    $stmt->close();
}



<div class="container">
    <div class="row">
        <?php bootloop($link); ?>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

如果您想对行的数组值进行分组,可以使用array_chunk() http://php.net/manual/en/function.array-chunk.php

此外,由于您以后不需要存储html并且行数相当小,我只会使用echo代替HEREDOC,因为我觉得它更具可读性。显然,如果你不想,你就不必这样做。

然后你会有类似的东西:

function bootloop($link)
{

    $stmt = $link->prepare("SELECT `prod_name` FROM `products`");
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result) {
        $prod_names = [];

        while ($row = $result->fetch_assoc()) {
            $prod_names[] = sanitize($row['prod_name']);
        }

        foreach (array_chunk($prod_names, 2) as $chunks) : ?>
            <div class="row">
                <?php foreach ($chunks as $prod_name) : ?>
                    <div class="col-md-6 text-center">
                        <?php echo $prod_name ?>
                    </div>
                <?php endforeach ?>
            </div>
        <?php endforeach;
    }

    $stmt->close();
}

或者,如果您不喜欢foreach循环的格式             上面你可以做多个打开和关闭php标签:

foreach (array_chunk($prod_names, 2) as $chunks) {
    echo '<div class="row">';
    foreach ($chunks as $prod_name) {
        echo "<div class='col-md-6 text-center'>$prod_name</div>";
    }
    echo '</div>';
}

修改

如果您想要获得产品的ID,请:

$stmt = $link->prepare("SELECT `id`, `prod_name` FROM `products`");

$products = [];

while ($row = $result->fetch_assoc()) {
    $products[] = [
        'id'   => $row['id'],
        'name' => sanitize($row['prod_name']),
    ];
}

foreach (array_chunk($products, 2) as $chunks) {
    echo '<div class="row">';
    foreach ($chunks as $product) {
        echo "<div class='col-md-6 text-center'>{$product['id']} {$product['name']}</div>";
    }
    echo '</div>';
}

在上面我现在将数据中每行的数据存储起来(我还将$prod_name(s)更改为$product(s)更合适)。尝试访问""内的数组值时,必须将值包装在{}中。

希望这有帮助!