如何将这个简单的数组转换为嵌套的php数组?

时间:2017-09-20 14:38:26

标签: php mysql multidimensional-array

嗨,我有这个包含类别层次结构的简单php数组

<?php

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

一旦回声,它将看起来像这样(一个简单的类别hierarychy):

Games
-Sports
--Footbal
--Basketball
-Action
--FPS
--RPG
-SIM

目前我想通过https://github.com/jonmiles/bootstrap-treeview使用Bootstrap Tree插件,并且需要准备我的数据看起来像这样

var tree = [
  {
    text: "Games",
    nodes: [
      {
        text: "Sports",
        nodes: [
          {
            text: "Footbal"
          },
          {
            text: "Basketball"
          }
        ]
      },
      {
        text: "Action",
        nodes: [
          {
            text: "FPS"
          },
          {
            text: "RPG"
          }
        ]
      },
      {
        text: "SIM"
      }
    ]
  }
];

我知道我需要先构建一个数组,然后再将其转换为JSON。问题是如何将现有数组转换为兼容数组以获取所需的JSON?

到目前为止我的代码

<?php

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

$tree_key = 0;

if (!empty($categories)) {
            foreach ($categories as $category) {

                $tree_label = $category;

                $count = substr_count($tree_label, '-');

                //if no dash (-) found, make it parent category
                if (empty($count)) {
                    $tree_key = $category;
                    $tree_array[$tree_key] = ['text'=>$category];
                }
                else
                {
                    //if one dash found, make it child of previous parent category
                    if ($count === 1) {
                        $tree_array[$tree_key]['nodes'][] = ['text'=>$category];
                    } else {

                    }
                }


            }
        }

谢谢大家帮忙!

1 个答案:

答案 0 :(得分:1)

试试这个:

function buildTree($data, $currentDepth = 0, $startIndex = 0) {
    $tree = array();
    foreach ($data as $i=>$c) {
        if ($i < $startIndex) {
            continue;
        }

        $depth = 0;
        if (preg_match('/^([-]*)/', $c, $m)) {
            $depth = strlen($m[1]);
        }

        if ($depth < $currentDepth) {
            break;
        } elseif ($depth != $currentDepth) {
            continue;
        }

        $node = array('text' => preg_replace('/^[-]*/', '', $c));
        $nodes = buildTree($data, $depth + 1, $i + 1);
        if (count($nodes) > 0) {    
            $node['nodes'] = $nodes;
        }

        $tree[] = $node;
    }
    return $tree;
}

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

echo json_encode( buildTree($categories), JSON_PRETTY_PRINT );

Online demo