Magento - Single Custom Product Attribute with Arr

2019-07-17 05:43发布

问题:

I have a need in Magento to provide an array custom product attribute that outputs all of its values as list items. The basic premise is a list of product ingredients... on a per product basis we need to enter (for example) water, salt, colourings - and for those to be rendered as a list on the front end.

My logic so far has been to use the standard text field attribute, entering comma separated values in the back-end and then to try and use that string as an array from which I can use foreach to create the unordered list.

So far I can echo the entire string as just one list item, but rendering the string as an array of its individual values has so far stumped me! See below...

The Ingredients text field attribute has a value of "water", "salt", "colourings". - the addition of quote marks and commas is only the assumption that this would pre-format the list ready to be an array.

<?php
$ingredientsArrayContent = $this->getProduct()->getSpa_productingredients();
$ingredientsArray = array($ingredientsArrayContent);
?>
<ul>
    <?php
    reset($ingredientsArray);
    foreach ($ingredientsArray as $ingredientsValue) {
        echo "<li>$ingredientsValue</li>\n";
    }
    ?>
</ul>

So on the front end this is outputting:

<ul>
    <li>"water", "salt", "colourings"</li>
</ul>

What of course I am looking to achieve is:

<ul>
    <li>water</li>
    <li>salt</li>
    <li>colourings</li>
</ul>

Am I over complicating this and missing something really obvious even in Magento? Any pointers greatly appreciated!!

回答1:

Perhaps instead of:

$ingredientsArray = array($ingredientsArrayContent);

try using:

$ingredientsArray = array(explode(",",$ingredientsArrayContent));

Depending on whether your attribute is set as: "water,salt,colourings" or "water, salt, colourings" your delimiter might need to change or how you set your attribute values might need to change.