You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Smarty中访问数组内哈希结构的amount字段

解决方法:先解析JSON字符串,再访问字段

从你给出的@print_r输出来看,tsh_promotion_details的值其实是一个JSON格式的字符串,而不是Smarty可以直接遍历的PHP数组/哈希结构。所以你需要先把它解析成PHP数组,然后才能访问里面的amount字段。

这里有两种常用的处理方式:

方式一:用Smarty内置修饰符直接解析

Smarty 3及以上版本支持@json_decode修饰符,可以直接把JSON字符串转成数组。你可以直接这样写:

{* 解析JSON后取第一个元素的amount字段 *}
{$position.attributes.tsh_promotion_details|@json_decode}[0].amount

如果想让代码更清晰,也可以拆分步骤:

{* 先把JSON解析成数组变量 *}
{assign var="promotion_list" value=$position.attributes.tsh_promotion_details|@json_decode}
{* 访问第一个促销项的amount值 *}
{$promotion_list[0].amount}

方式二:在PHP后端提前处理

如果你的Smarty版本不支持@json_decode,或者希望模板逻辑更简洁,可以在把变量传递给Smarty之前,在PHP代码里先完成JSON解析:

// 假设$position是准备传给Smarty的变量
$position['attributes']['tsh_promotion_details'] = json_decode($position['attributes']['tsh_promotion_details'], true);
// 再将处理后的$position传递给Smarty模板

之后在模板里就能直接访问了:

{$position.attributes.tsh_promotion_details[0].amount}

补充说明

之前你尝试直接访问失败,是因为Smarty把tsh_promotion_details的内容当作普通字符串处理了——@print_r只是把字符串内容打印出来,但并没有改变它的类型。只有转成PHP数组后,才能用数组索引和字段访问语法拿到amount的值。

内容的提问来源于stack exchange,提问作者K Nugal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:39