如何在php的数组的父项下显示子项

时间:2013-03-12 12:58:04

标签: php arrays wordpress for-loop

我有一个这样的数组:

Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [menu_item_parent] => 0
            [title] => Home
            [url] => http://www.example.com/
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [menu_item_parent] => 0
            [title] => Menu 2
            [url] => http://www.example.com/menu-2/
        )

    [2] => stdClass Object
        (
            [ID] => 3
            [menu_item_parent] => 2
            [title] => Sub Menu 1
            [url] => http://www.example.com/menu-2/sub-menu-1
            [target] => 
        )

    [3] => stdClass Object
        (
            [ID] => 4
            [menu_item_parent] => 0
            [title] => Menu 4
            [url] => http://www.example.com/menu-4/
            [target] => 

        )
)

现在您可以看到数组的第3项是第二个数组项的子项(请参阅列menu_item_parent)。现在我的问题是如何使用此数组显示此父项与其子项。请帮忙。

6 个答案:

答案 0 :(得分:5)

最后在@ Matt.C给出链接的帮助下解决了我的问题。谢谢@Matt.C。这是解决方案:

首先将菜单项设为平面阵列:

<?php
$menu_name = 'main_nav';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
?>

然后迭代菜单项的数组:

<nav>
<ul class="main-nav">
    <?php
    $count = 0;
    $submenu = false;

    foreach( $menuitems as $item ):
        // get page id from using menu item object id
        $id = get_post_meta( $item->ID, '_menu_item_object_id', true );
        // set up a page object to retrieve page data
        $page = get_page( $id );
        $link = get_page_link( $id );

        // item does not have a parent so menu_item_parent equals 0 (false)
        if ( !$item->menu_item_parent ):

        // save this id for later comparison with sub-menu items
        $parent_id = $item->ID;
    ?>

写下第一个父项<li>:

 <li class="item">
        <a href="<?php echo $link; ?>" class="title">
            <?php echo $page->post_title; ?>
        </a>
        <a href="<?php echo $link; ?>" class="desc">
            <?php echo $page->post_excerpt; ?>
        </a>
    <?php endif; ?>

检查此项的父ID是否与存储的父ID匹配:

     <?php if ( $parent_id == $item->menu_item_parent ): ?>
Start sub-menu <ul> and set $submenu flag to true for later referance:

            <?php if ( !$submenu ): $submenu = true; ?>
            <ul class="sub-menu">
            <?php endif; ?>
Write the sub-menu item:

                <li class="item">
                    <a href="<?php echo $link; ?>" class="title"><?php echo $page->post_title; ?></a>
                    <a href="<?php echo $link; ?>" class="desc"><?php echo $page->post_excerpt; ?></a>

如果下一个项目没有相同的父ID,我们宣布了一个子菜单,那么关闭子菜单<ul>

<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
        </ul>
        <?php $submenu = false; endif; ?>

<?php endif; ?>

同样,如果数组中的下一个项目没有相同的父ID,请关闭<li>

  <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
    </li>                           
    <?php $submenu = false; endif; ?>

<?php $count++; endforeach; ?>
  </ul>
</nav> 

答案 1 :(得分:2)

试试这个:我将输入添加为数组,根据您的问题更改为对象。

$array  = Array( array("ID" => 1,"menu_item_parent" => 0,"title" => "Home","url" => "http://www.example.com/"),
                 array("ID" => 2,"menu_item_parent" => 0,"title" => "Menu 2","url" => "http://www.example.com/menu-2/"),
                 array("ID" => 3,"menu_item_parent" => 2,"title" => "Sub Menu 1","url" => "http://www.example.com/menu-2/sub-menu-1","target" =>"" ),
                 array("ID" => 4,"menu_item_parent" => 0,"title" => "Menu 4","url" => "http://www.example.com/menu-4/","target" => "")
          );

$res   = array();         
foreach($array as $val){
   if($val['menu_item_parent'] != 0){
       $res[$val['menu_item_parent']]['child'][] = $val;
   }
   else{
       $res[$val['ID']] = $val;
   }
}

echo "<pre>";
print_r($res);

输出:

Array
(
    [1] => Array
        (
            [ID] => 1
            [menu_item_parent] => 0
            [title] => Home
            [url] => http://www.example.com/
        )

    [2] => Array
        (
            [ID] => 2
            [menu_item_parent] => 0
            [title] => Menu 2
            [url] => http://www.example.com/menu-2/
            [child] => Array
                (
                    [0] => Array
                        (
                            [ID] => 3
                            [menu_item_parent] => 2
                            [title] => Sub Menu 1
                            [url] => http://www.example.com/menu-2/sub-menu-1
                            [target] => 
                        )

                )

        )

    [4] => Array
        (
            [ID] => 4
            [menu_item_parent] => 0
            [title] => Menu 4
            [url] => http://www.example.com/menu-4/
            [target] => 
        )

)

答案 2 :(得分:1)

在php中使用foreach函数检查。 像

$array = array("apple" => 1, "orange" => 2);
$sep = "";
foreach($array as $key => $value) {
  if($sep) {
    $sep .= "<br/>key:".$key." / value:".$value;
  } else {
    $sep = "key:".$key." / value:".$value;
  }
} 

<强>输出:

key:apple / value:1
key:orange / value:2

答案 3 :(得分:1)

您可以迭代数组,如果对象有父对象,则将其添加到该父对象的children数组中。例如:

$array = array(

  1 => (object) array('menu_item_parent' => 0),
  2 => (object) array('menu_item_parent' => 1),
  3 => (object) array('menu_item_parent' => 0),

);

foreach ($array as $key => $object)
{

  if (0 != $object->menu_item_parent && isset($array[$object->menu_item_parent]))
  {

    if (!property_exists($array[$object->menu_item_parent], 'children'))
    {
        $array[$object->menu_item_parent]->children = array();
    }

    $array[$object->menu_item_parent]->children[] = $object;

    unset($array[$key]);    

  }

}

echo '<pre>' . print_r($array, TRUE) . '</pre>';

将转换:

Array
(
    [1] => stdClass Object
        (
            [menu_item_parent] => 0
        )

    [2] => stdClass Object
        (
            [menu_item_parent] => 1
        )

    [3] => stdClass Object
        (
            [menu_item_parent] => 0
        )

)

要:

Array
(
    [1] => stdClass Object
        (
            [menu_item_parent] => 0
            [children] => Array
                (
                    [0] => stdClass Object
                        (
                            [menu_item_parent] => 1
                        )

                )

        )

    [3] => stdClass Object
        (
            [menu_item_parent] => 0
        )

)

然后,您可以迭代每个对象并在需要时显示其子项:

foreach ($array as $object)
{

  echo 'Parent: ' . $object->title . '<br>';

  if (property_exists($object, 'children') && !empty($object->children))
  {

    echo '&nbsp;&nbsp;&nbsp;Children: ';

    foreach ($object->children as $child)
    {
      echo $child->title . '<br>';
    }

  }

}

答案 4 :(得分:1)

这是一个非常简单的类,针对您的Wordpress特定问题,使用get_submenu函数返回所有子菜单项:

class NestedMenu
{
    private $flat_menu;
    public $items;

    function __construct($name)
    {
        $this->flat_menu = wp_get_nav_menu_items($name);
        $this->items = array();
        foreach ($this->flat_menu as $item) {
            if (!$item->menu_item_parent) {
                array_push($this->items, $item);
            }
        }
    }

    public function get_submenu($item)
    {
        $submenu = array();
        foreach ($this->flat_menu as $subitem) {
            if ($subitem->menu_item_parent == $item->ID) {
                array_push($submenu, $subitem);
            }
        }
        return $submenu;
    }
}

用法。构建实例:

$menu = new NestedMenu('menu_name');

迭代:

foreach ($menu->items as $item) { ...

获取循环内的子菜单:

$submenu = $menu->get_submenu($item);

在显示子菜单之前,您可以检查它是否存在:

if ($submenu): ...

答案 5 :(得分:0)

这将是我的解决方案。将父对象下的子项移动到children,并在名为has_child的父项下创建一个布尔值,其值为1。最后,取消设置并从主变量中删除子项。

$elements = wp_get_nav_menu_items("theme-location");

foreach($elements as $index => $item)
{
    if($item->menu_item_parent != 0)
    {
        foreach($elements as $index2 => $item2)
        {
            if($item2->ID == $item->menu_item_parent)
            {
                $elements[$index2]->has_child = true;

                if(!isset($elements[$index2]->children))
                {
                    $elements[$index2]->children = array();
                }
                $elements[$index2]->children[] = $item;
            }
        }
        unset($elements[$index]);           
    }
}