问题
I have an array which I created in php with a recursive function, I do not know how many dimensions, how can I use in Smarty ?
I trying use this code :
{foreach $myArr as $items}
<li>
{$items.title}
{if $item.submenu}
<ul>
{foreach $items.submenu as $items2}
<li>{$items2.title}</li>
{/foreach}
</ul>
{/if}
</li>
{/foreach}
But this code is for just 2 levels, may be my array have 3 or 4 or ... levels.
UPDATE:
I found the solution, in my solution I use Smarty functions :
{function name=menu level=0}
<ul>
{foreach $data as $items}
<li>
<a href="{$items.url}">
{$items.title}
</a>
{if is_array($items.submenu)}
{menu data=$items.submenu level=$level+1}
{/if}
</li>
{/foreach}
</ul>
{/function}
{menu data=$menuItems}
回答1:
I would go a different approach. My suggestion: Instead of creating arrays with menus. Create two or one class/es.
First class is a Menu class which holds the items in a key/value manner. Second class would be a menu item.
That way you could all necessary iterations/logic do through a function call in the model and the printing in the view.
something like:
class Menu {
protected $_items = array();
protected $_parent_child = array();
public function add_menu_item($name, $id, $parent_id) {
if (array_key_exists($id, $this->_items))
return;
$this->_items[$i] = array('name' => $name, 'id' => $id, 'parent' => $parent_id) // model with data
$this->_parent_child[$parent_id] = $this->_items[$id];
}
public function get_nodes_by_parent($id=null /*for root*/) {
if (array_key_exists($id, $this->_parent_child))
return $this->_parent_child[$id];
return array(); // or null or something
}
}
Menu template:
{foreach($menuClass->get_nodes_by_parent() as $item ) {
<ul>
<li>{$item['name']}</li>
{include 'sub_cats' id=$item['id'], menuclass=$menuclass}
</ul>
{endforeach}
Sub category template:
{foreach($menuClass->get_nodes_by_parent($id) as $item ) {
<ul>
<li>{$item['name']}</li>
{include 'sub_cats' id=$item['id']}
</ul>
{endforeach}
This is not fully complete nor tested. But that would be my approach.
来源:https://stackoverflow.com/questions/14342645/how-to-foreach-an-array-variable-created-with-recursive-function-in-smarty