【问题标题】:Dynamic array with string key带字符串键的动态数组
【发布时间】:2015-07-23 00:27:57
【问题描述】:

我有数组:

Array
(
[CS] => Array
    (
        [Zomblerz] => 1.80
        [Quintic] => 2.06
        [Mostly Harmless] => 2.21
        [Nexus eSports] => 1.70
        [WinOut.net] => 2.73
        [Ace Gaming] => 1.48
        [Luminosity Gaming] => 3.68
        [Natus Vincere] => 1.30
    )

[LoL] => Array
    (
        [Jin Air Green Wings] => 1.17
        [Incredible Miracle] => 5.40
        [Rebels Anarchy] => 1.27
        [SBENU Sonicboom] => 3.92
        [SK Telecom T1] => 1.19
        [CJ Entus] => 4.95
        [KOO Tigers] => 1.38
        [NaJin e-mFire] => 3.15
    )

[StarCraft] => Array
    (
        [Maru] => 1.48
        [Zest] => 2.73
        [Stats] => 1.90
        [ByuL] => 1.94
    )
)

我想用 {section} 在 Smarty 中显示我的数组,但我有一个字符串索引键并且不能这样做。 我试过 {foreach},但结果太糟糕了。

{section name=i loop=$odds}
<table>
  <th> here i want game name... </th>
  {section name=j loop=$odds[i]}
  <tr>
     <td> here team name - here team number </td>
     ...
  </tr>
  {/section}
 </table>
 {/section}

你能帮帮我吗?

附:对不起我的英语(

【问题讨论】:

标签: php arrays smarty


【解决方案1】:

在 smarty 中可能有更好的方法来获得你想要的东西。但是如果你只需要带有数字键的数组,你可以使用array_values();在数组上,它将重新索引键,

http://php.net/manual/en/function.array-values.php

【讨论】:

    【解决方案2】:

    {section} 仅用于循环遍历数字索引数组

    {foreach} 用于循环关联数组

    您想要的结果显示在Example 7.8. {foreach} with nested item and key - http://www.smarty.net/docsv2/en/language.function.foreach.tpl#id2802172

    你的代码看起来像 -

    {foreach key=game item=odd from=$odds}
      <table>
      <th>{$game}</th>
      {foreach key=team item=teamnumber from=$odd}
        <tr>
          <td>{$team}: {$teamnumber}</td>
        </tr>
      {/foreach}
      </table>
    {/foreach}
    

    编辑

    根据您的评论,如果您想更改表格布局,请使用

    {if $smarty.foreach.teams.index % 2 == 0}...{/if}
    

    你可以做类似的事情 -

    {foreach key=game item=odd from=$odds}
      <table>
      <th>{$game}</th>
        <tr>
      {foreach name=teams key=team item=teamnumber from=$odd}
        {if $smarty.foreach.teams.index % 2 == 0}
        </tr>
        <tr>
        {/if}
          <td>{$team}</td>
          <td>{$teamnumber}</td>
      {/foreach}
        </tr>
      </table>
    {/foreach}
    

    http://www.smarty.net/docsv2/en/language.function.foreach.tpl#foreach.property.index

    【讨论】:

    • 非常感谢。但是,如果我想像这样将两支球队和两个数字排成一行:
      game1
      team1 odd1 team2 odd2
      team3 odd3 team4 odd4
      ,foreach能做到吗?
    • 如果这是你想要的结果,为什么你没有把它放在你原来的问题中?
    • 我是Smarty的新手,正在学习所有案例)再次寻求帮助,开始阅读手册)
    • 在你的例子中只有偶数索引,但我希望两个团队在 foreach 循环的一个步骤中...... Smarty 可以做到吗?文档没有这种情况的例子(
    • 我对此表示怀疑,因为foreach 的意思是for-each。请注意我如何使用模数 - % 2 == 0。这允许您在每 2 之后执行一些操作,这可能是创建一个新行或其他 html。用你想要的结果更新你的问题,因为很难知道你想要什么。
    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多