为动态手风琴创建关联数组php

时间:2016-07-28 06:01:57

标签: php arrays

您好我正在使用数据库中的值创建一个动态的手风琴。

我被困在循环数组中。请帮忙。

我有一个与此类似的数组

Array
(
[0] => Array
    (
        [0] => Array
            (
                [0] => real estate
            )

        [1] => Array
            (
                [0] => flatvcvjh
                [1] => villayuiuyidd
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [0] => real estate
                [1] => iooi
            )

        [1] => Array
            (
                [0] => y
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [0] => real estate
                [1] => iooi
                [2] => painting
            )

        [1] => Array
            (
                [0] => interior
                [1] => exterior
            )

    )

[3] => Array
    (
        [0] => Array
            (
                [0] => real estate
                [1] => iooi
                [2] => painting
                [3] => contruction
            )

        [1] => Array
            (
                [0] => house
                [1] => compound
            )

    )

)

Following is the loop m using to get the above array
 foreach($parent_categories as $parent_category) {

         $sub_categories=//array of sub cat;
         $arr[]=$parent_category->name;

         $scat_name="";
         foreach($sub_categories as $sub_category) {
            //get sub categories
             $scat_name[]=$sub_category->name;
         }
         $subcat_name[]=$arr;
         $subcat_name[]=$scat_name;
         $project_categories[] = $subcat_name;
         $subcat_name="";

    }
echo "<pre>";
    print_r($project_categories);exit;

我试过的上述循环是2级。

我需要一个包含3个级别的3维数组 喜欢

category1
  subcat1
  subcat2
     subsubcat1
     subsubcat2
  subcat3

我必须在上面的循环中做出什么改变我尝试了多种方式以上是我得到的。请帮忙

2 个答案:

答案 0 :(得分:2)

使用递归函数

$menusList = array();
function dynamic_menus($menus) {
  foreach($menus as $index => $subMenu) {
   menusList[$index] = is_array($subMenu) ? dynamic_menus($subMenu) : $subMenu;
  }
 return menusList;
}

答案 1 :(得分:0)

您需要先将数组转换为对象,因为您使用

  
    

$ sub_category-&gt; name是读取对象类型

  

Multidimensional array to object, specific way

http://php.net/manual/en/language.types.object.php