PHP 到 Smarty,显示一些嵌套数组
我在 smarty 中显示一些嵌套数组结果时遇到一些问题...这就是我所拥有的:
$searchResults
- 一个数组,其中每一行都是一个结果集。这里没问题。 $searchResults[$row][users][]
- 这是我创建的嵌套数组。如果搜索结果的这一行存在用户,我想显示每个用户...
所以,这里我们有我的聪明代码:
{section name=i loop=$searchResults}
{section name=j loop=$searchResults[i].users}
{$searchResults[i].users[j].firstName}
{/section}
{/section}
但是,这似乎不适合我...它显示用户结果以一种疯狂的方式在我的表格中,而不是位于该部分所在的同一个 内。
更新 - 使用 For Each,使用更多代码...
{section name=i loop=$searchResults}
<tr>
<td>{$searchResults[i].id}</td>
<td>
{if $searchResults[i].users}
{foreach from=$searchResults[i].users item=user}
{$user.firstName} {$user.lastName} <br>
{/foreach}
{/if}
</td>
</tr>
{/section}
这将显示一个如下所示的表格:
ID
ID
ID
Bob Boberton
John Appleton
Chris Cooley
Carl Agley
Cynthia Nobody
当它应该是这样的时:
ID Bob Boberton
John Appleton
ID Chris Cooley
ID Carl Agley
Cynthia Nobody
I'm having some issues displaying some nested array results in smarty... here's what I have:
$searchResults
- an array, where each row is a result set. No problem here.$searchResults[$row][users][]
- this is the nested array I created. If users exist for this row of the search results, I want to display every user....
So, here we have my smarty code:
{section name=i loop=$searchResults}
{section name=j loop=$searchResults[i].users}
{$searchResults[i].users[j].firstName}
{/section}
{/section}
However, this doesn't seem to work out for me... it displays the users results in a crazy fashion in my table, instead of being inside the same <td></td>
where the section is placed inside.
UPDATE - Using For Each, with more code...
{section name=i loop=$searchResults}
<tr>
<td>{$searchResults[i].id}</td>
<td>
{if $searchResults[i].users}
{foreach from=$searchResults[i].users item=user}
{$user.firstName} {$user.lastName} <br>
{/foreach}
{/if}
</td>
</tr>
{/section}
This displays a table like this:
ID
ID
ID
Bob Boberton
John Appleton
Chris Cooley
Carl Agley
Cynthia Nobody
When it should be like this:
ID Bob Boberton
John Appleton
ID Chris Cooley
ID Carl Agley
Cynthia Nobody
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以更进一步,为主循环使用另一个
foreach
。我发现它们更容易阅读并找到问题所在。也就是说,我无法通过
$searchResults
的描述方式重现您的问题;你的循环和我的循环最终效果相同。下面是我正在使用的数组。You could go further and use another
foreach
for the main loop. I've found them to be easier to read and find what the issue is.That said, I could not reproduce your issue with how
$searchResults
was described; both your loop and mine worked the same in the end. Below is the array I was using.