2017-09-20 62 views
2

您好我有这个简单的PHP数组包含类别层次如何将这个简单的数组转换为嵌套的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和需要准备我的数据看起来像这样

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

我明白,我需要建立一个数组FIR st,然后将其转换为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 { 

        } 
       } 


      } 
     } 

谢谢你们的帮助!

+0

你只需要这一个JSON对象,或者你想代码,可以做到这一点无论数组是什么 –

+0

作为树是一个递归数据模型我会建议这个问题的递归方法 – gogaz

+0

@MatthewBergwall取决于破折号( - )的数量,我想保持它的嵌套,但通常数据是非常像上面的例子,所以如果我能够实现那已经很好:) –

回答

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

+0

感谢您的答案完美工作,看着您的代码我不知道如何达到写这种代码的水平。再次感谢@brevis先生 –

相关问题