原数组格式
$tdata=
Array
(
[0] => Array
(
[id] => 1
[fid] => 0
[l_title] => 今日头条
[l_key] => 今日头条
[l_desc] => 今日头条
[l_ico] => ../upload/images/14842284478853.jpg
[l_module] => article
[l_hidden] => 0
)
[1] => Array
(
[id] => 2
[fid] => 11
[l_title] => 头条新闻
[l_key] => 头条新闻
[l_desc] => 头条新闻
[l_ico] =>
[l_module] => article
[l_hidden] => 0
)
[2] => Array
(
[id] => 11
[fid] => 0
[l_title] => 明日新闻
[l_key] => 明日新闻
[l_desc] => 明日新闻
[l_ico] =>
[l_module] => article
[l_hidden] => 0
)
)
需求:fid为上级分类ID,使用smarty模板引擎时需输出上级分类名称,而不是ID。即数组元素fid修改成分类名称。
已有函数get_list_name($id),可通过分类id获取分类名称。
代码片段
//上级菜单ID替换成菜单名
foreach($tdata as $row){
foreach($row as $k=>$v){
if($k=='fid'){
if($row[$k]==0){
$row[$k] = '顶级分类';
}else{
$row[$k] = get_list_name($v);
}
}
}
$data[] = $row;
}
//上级菜单ID替换成菜单名
$data即为新数组,格式为
Array
(
[0] => Array
(
[id] => 1
[fid] => 顶级分类
[l_title] => 今日头条
[l_key] => 今日头条
[l_desc] => 今日头条
[l_ico] => ../upload/images/14842284478853.jpg
[l_module] => article
[l_hidden] => 0
)
[1] => Array
(
[id] => 2
[fid] => 明日新闻
[l_title] => 头条新闻
[l_key] => 头条新闻
[l_desc] => 头条新闻
[l_ico] =>
[l_module] => article
[l_hidden] => 0
)
[2] => Array
(
[id] => 11
[fid] => 顶级分类
[l_title] => 明日新闻
[l_key] => 明日新闻
[l_desc] => 明日新闻
[l_ico] =>
[l_module] => article
[l_hidden] => 0
)
)
最后通过赋值即可在模板中循环使用。
代码:
$smarty -> assign('list', $data);//给变量赋值
模板中代码:
{foreach item=li from=$list}
<tr>
<td>{$li.id}</td>
<td>{$li.fid}</td>
<td>{assign var="module" value="{$lng.{$li.l_module}}"}
{$module}</td>
<td>{$li.l_title}</td>
<td>{$li.l_key}</td>
<td>{$li.l_desc}</td>
<td><a href="list.php?module={$li.l_module}&type=edit&id={$li.id}">编辑</a> <a href="list.php?module={$li.l_module}&type=del&id={$li.id}">删除</a></td>
</tr>
{/foreach}