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


How to show child item under its parent item of an array in php

我有一个这样的数组:

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] => 
        )
)

现在可以看到数组的第三个元素是第二个元素的子元素(参见menu_item_parent列)。现在我的问题是我如何显示这个父项目与它的子项目使用这个数组。请帮助。

最后在@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> 

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

$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] => 
        )
)

这里有一个非常简单的类,用于解决您的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): ...

可以遍历数组,如果对象有父对象,则将其添加到该父对象的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>';
    }
  }
}

检查在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

这就是我的解决方案。将父对象下的子对象移动到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]);           
    }
}