树菜单数组php

时间:2014-03-13 20:55:47

标签: php arrays uinavigationbar

我无法解决这个问题

Array
(
    [0] => Array
        (
            [id] => 1
            [menu] => shoes
            [anchor] => Shoes
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 2
            [menu] => futsal-shoes
            [anchor] => Futsal Shoes
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 3
            [menu] => lamps
            [anchor] => Lamps
            [parent] => 0
        )

    [3] => Array
        (
            [id] => 4
            [menu] => desk-lamps
            [anchor] => Desk Lamps
            [parent] => 3
        )

    [4] => Array
        (
            [id] => 5
            [menu] => floor-lamps
            [anchor] => Floor Lamps
            [parent] => 3
        )

    [5] => Array
        (
            [id] => 6
            [menu] => swing-arm-lamps
            [anchor] => Swing Arm Lamps
            [parent] => 4
        )

)

此函数显示所有数组

function has_children($rows,$id) {
    foreach ($rows as $row) {
        if ($row['parent'] == $id)
        return true;
    }
    return false;
}
function build_menu($rows,$parent=0) {  
    $result = "<ul>";
    foreach ($rows as $row) {
        if ($row['parent'] == $parent) {
            $result .= "<li><a href=\"$row[menu]\">$row[anchor]</a>";
        if (has_children($rows,$row['id']))
            $result.= build_menu($rows,$row['id']);
            $result .= "</li>";
        }
    }
    $result.= "</ul>";
    return $result;
}
echo build_menu($array);

我需要从页面

仅显示相关的树状菜单

如果GET类别=灯具

或GET subategory = floor-lamps

或GET sub_subcategory = swing-arm-lamps

它们只显示相关的(不是所有数组)

<ul>
    <li><a href="">Lamps</a>
    <ul>
        <li><a href="">Desk Lamps</a></li>
        <ul>
            <li><a href="">Swing Arm Lamps</a></li>
        </ul>
        <li><a href="">Floor Lamps</a></li>
    </ul>
</ul>

任何人都会帮助我。

3 个答案:

答案 0 :(得分:0)

这是一种适合您的方法。此代码低于您的功能。基本上我们从GET数组中获取一个变量并将其分配给$ current_menu。然后我们使用foreach来获取该特定菜单项的id(如果数组的键是[&#39; menu&#39;]项目,这将更简单)并将其分配给$ parent。最后,我们将$ parent传递给build_menus函数。

//A terse way to do it, instead of typing out all those GETs
//NOTE: This assumes you'll only have one of these at a time.
$cats = array("category", "subcategory", "sub_subcategory");
foreach ($cats as $cat) {
    if (isset($_GET[$cat])) {
        $current_menu = $_GET[$cat];    
    }
}

foreach ($array as $arr) {
    if ($current_menu == $arr['menu']) {
        $parent = $arr['parent'];   
    }
}

echo build_menu($array, $parent);

答案 1 :(得分:0)

SQL:

    CREATE TABLE `thematic_tree` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) unsigned NOT NULL,
  `name` varchar(50) NOT NULL,
  `description` varchar(1000) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

PHP:

class Thematic {

private $thematics;

public function __construct($database) {

    $this->database = $database;
    $this->thematics = $this->Init();
}

private function Init() {
    $result = [];
    $SQL = "SELECT * FROM thematic_tree;"; 
    if ($res = $this->database->query($SQL) ) {
        while ($row = $res->fetch_assoc()) $result[] = $row;
        $res->close();
    }
    return $result;
}

private function createTree(&$list, $parent){
    $tree = array();
    foreach ($parent as $k=>$l){
        if(isset($list[$l['id']])){
            $l['childs'] = $this->createTree($list, $list[$l['id']]);
        }
        $tree[] = $l;
    }
    return $tree;
}

public function getTree(){
    $new = array();
    foreach ($this->thematics as $a){
        $new[$a['parent_id']][] = $a;
    }
    return $this->createTree($new, $new[0]);
}

TWIG:

        {% macro menu_links(thematics, base_path) %}
        {% for item in thematics %}
            <li>
                <a href="{{ base_path }}/thematic/{{ item.id }}">{{ item.name }}</a>
                {% if item.childs %}
                    <ul>
                        {{ _self.menu_links(item.childs, base_path) }}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endmacro %}

    {% import _self as macros %}
    <ul class="main-menu">
        {{ macros.menu_links(thematics, base_path) }}
    </ul>

答案 2 :(得分:0)

尽管如此,它有点冗长:

<?php

$flat = array(
    array('id' => 1, 'parent' => 0, 'menu' => 'shoes', 'anchor' => 'Shoes'),
    array('id' => 2, 'parent' => 1, 'menu' => 'futsal-shoes', 'anchor' => 'Futsal Shoes'),
    array('id' => 3, 'parent' => 0, 'menu' => 'lamps', 'anchor' => 'Lamps'),
    array('id' => 4, 'parent' => 3, 'menu' => 'desk-lamps', 'anchor' => 'Desk Lamps'),
    array('id' => 5, 'parent' => 3, 'menu' => 'floor-lamps', 'anchor' => 'Floor Lamps'),
    array('id' => 6, 'parent' => 4, 'menu' => 'swing-arm-lamps', 'anchor' => 'Swing Arm Lamps'),
);

$root = array(
    'children' => array_tree_expand($flat, 'id', 'parent')
);

$query = array('menu' => 'shoes');

if (empty($query)) {
    build_menu_children($root['children']);
}
else {
    $item = array_tree_find($root, array('menu' => 'shoes'));
    if ($item) {
        build_menu($item);
    }
    else {
        echo 'error: not found';
    }
}
echo "\n";

function build_menu($root)
{
    echo '<ul><li>';
    echo sprintf('<a href="%s">%s</a>', htmlspecialchars($root['menu']), htmlspecialchars($root['anchor']));
    if ($root['children']) {
        build_menu_children($root['children']);
    }
    echo '</li></ul>';
}

function build_menu_children(array $children)
{
    echo '<ul>';
    foreach ($children as $child) {
        echo '<li>';
        echo sprintf('<a href="%s">%s</a>', htmlspecialchars($child['menu']), htmlspecialchars($child['anchor']));
        if (count($child['children'])) {
            build_menu_children($child['children']);
        }
        echo '</li>';
    }
    echo '</ul>';
}

function array_tree_find(array $root, array $query)
{
    $match = true;
    foreach ($query as $k => $v) {
        if (!array_key_exists($k, $root)) {
            $match = false;
            break;
        }
        if ($root[$k] !== $query[$k]) {
            $match = false;
            break;
        }
    }
    if ($match) {
        return $root;
    }

    foreach ($root['children'] as $child) {
        $found = array_tree_find($child, $query);
        if ($found !== null) {
            return $found;
        }
    }

    return null;
}

// http://stackoverflow.com/a/25478474
function array_tree_expand(array $array, $id = 'id', $parent = 'pid', $children = 'children')
{
    $r = array();
    foreach ($array as $v) {
        $k = $v[$id];
        $r[$k] = $v;
        $r[$k][$children] = array();
    }
    $adopted = array();
    foreach ($r as $k => $v) {
        if (isset($r[$v[$parent]])) {
            $r[$v[$parent]][$children][] = &$r[$k];
            $adopted[] = $k;
        }
    }
    foreach ($adopted as $id) {
        unset($r[$id]);
    }
    return $r;
}

function array_tree_flatten(array $tree, $children = 'children', $level = 'level')
{
    $spec = compact('children', 'level');
    $ret = array();
    array_tree_flatten_walk($ret, $tree, $spec);
    return $ret;
}

function array_tree_flatten_walk(array &$ret, array $tree, array $spec, $level = 0)
{
    foreach ($tree as $child) {
        $children = $child[$spec['children']];
        unset($child[$spec['children']]);
        $child[$spec['level']] = $level;
        $ret[] = $child;
        array_tree_flatten_walk($ret, $children, $spec, $level + 1);
    }
}

您可以保存到a.php和运行php a.php

相关问题