温馨提示:本文翻译自stackoverflow.com,查看原文请点击:php - Create function and call it
function php call

php - 创建函数并调用它

发布于 2020-03-29 21:58:35

我有一段代码需要多次使用,但是我不想用很多相同的代码来弄一个很长的页面。

我有这段代码:

<div class="av-product-specs-list-container">
    <input type="checkbox" id="chck1" checked>
    <label class="av-product-specs-title" for="chck1">Algemene informatie</label>
    <div class="av-product-specs-table-list first-spec-list">

        <?php if( $av_merk != "" ) : ?>
            <div class="av-product-specs-table-row">
                <div class="av-product-specs-table-row-left">Merk</div>
                <div class="av-product-specs-table-row-right">
                    <?php echo $av_merk; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php 
            $av_attribute_group = $_product->getAttributes(37);

            foreach ($av_attribute_group as $av_attribute_groups):

                $av_attr_name = $av_attribute_groups->getName();
                $av_attr_label = $_product->getResource()->getAttribute($av_attr_name)->getFrontend()->getLabel($_product);
                $av_attr_value = $_product->getResource()->getAttribute($av_attr_name)->getFrontend()->getValue($_product);

                if( $av_attr_value != "" ) :

                ?>

                    <div class="av-product-specs-table-row">
                        <div class="av-product-specs-table-row-left"><?php echo $av_attr_label; ?></div>
                        <div class="av-product-specs-table-row-right">
                            <?php 
                                if( $av_attr_value == "Yes" || $av_attr_value == "Ja" ) : ?>
                                    <div class="av-spec-yes"></div>
                                <?php elseif( $av_attr_value == "No" || $av_attr_value == "Nee" ) : ?>
                                    <div class="av-spec-no"></div>
                                <?php else : 
                                    echo $av_attr_value;
                                endif; 
                            ?>
                        </div>
                    </div>

                <?php endif; ?>             
        <?php endforeach ?>

    </div>
</div>

无需创建这段代码超过40次,我需要创建一个可以调用的函数,只需更改$ av_attribute_group = $ _product-> getAttributes(37);。因为我需要引导不同的ID。

我怎样才能做到这一点?

查看更多

提问者
n00bly
被浏览
120
Nick 2020-01-31 18:59

您可以只将代码括在function声明中。您需要包含$_product$av_merk变量作为参数,还需要传递一个$id值以传递给$_product->getAttributes例如:

function show_av($_product, $av_merk, $id) {
?>
... your code
<?php
}

show_av($_product, $av_merk, 37);
?>

在您的代码中,然后您将替换

$av_attribute_group = $_product->getAttributes(37);

$av_attribute_group = $_product->getAttributes($id);