php 如何在 smarty 模板中访问数组的键和值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20966164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:42:34  来源:igfitidea点击:

How to access key and value of an array in smarty template?

phparraysforeachsmarty

提问by PHPLover

I'm assigning an array named $enquiries_labelsfrom php file to a smarty template file. If I print the array in PHP file it's output is as follows:

我正在将一个$enquiries_labels从 php 文件命名的数组分配给一个 smarty 模板文件。如果我在 PHP 文件中打印数组,它的输出如下:

Array
(
    [0] => New Enquiry
    [1] => Retail Enquiry
    [2] => Feedback
    [3] => Payment Query
    [4] => Package Query
    [5] => Test Query
)

Now after assigning this array to a smarty file I want to access these values in a select HTML control. For it I need to use foreach loop construct of smarty template engine. If a pre-selected value is matching with the key from array then I'll keep that value selected. For achieving this I tried below code, but it didn't work for me. Can anyone help me in this regard please? For your reference I'm putting below the code I tried in smarty template:

现在,在将此数组分配给 smarty 文件后,我想在选择的 HTML 控件中访问这些值。为此,我需要使用 smarty 模板引擎的 foreach 循环构造。如果预先选择的值与数组中的键匹配,那么我将保持选择该值。为了实现这一点,我尝试了下面的代码,但它对我不起作用。任何人都可以在这方面帮助我吗?供您参考,我将在 smarty 模板中尝试的代码放在下面:

<select name="contact_label" id="contact_label"> 
{if $enquiries_labels}
                  {foreach from=$enquiries_labels item=label}
                    <option value="{$label.key}" {if $data.key == $label.key} selected="selected" {/if}>{$label.value}
                    </option>
                  {/foreach}
                {/if}
      </select>

Thanks for spending some of your valuable time in understanding my issue.

感谢您花费一些宝贵的时间来了解我的问题。

回答by Bart Friederichs

Use keyin your foreach:

使用key您的foreach

{foreach from=$enquiries_labels item=label key=key}
          <option value="{$key}" {if $data.key == $key} selected="selected" {/if}>{$label}
          </option>
{/foreach}

It's all there in the documentation.

这一切都在文档中

回答by SerzN1

Smarty 3 foreach construction is like this

Smarty 3 foreach 构造是这样的

{foreach $products as $p}
    {$p@key}: {$p}
{/foreach}

回答by Rico Sonntag

Use the keyattribute.

使用key属性。

{foreach from=$enquiries_labels item="label" key="key"}
    <option value="{$key}"{if $data.key == $key} selected="selected"{/if}>{$label}</option>
{/foreach}

回答by Alp Altunel

this also works

这也有效

{foreach $products as $product}
    key: {$product@key} -> value: {$product@value} 
{/foreach}

{$product@value} = {$product}