2017-09-20 2 views
2

こんにちは、私はカテゴリ階層この単純な配列をネストされたPHP配列に変換するには?

<?php 

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

を含むこの単純なPHPの配列は、一度それがこの(簡単なカテゴリ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" 
     } 
    ] 
    } 
]; 

を見るために私のデータを準備する必要があることで、私は、配列のモミを構築する必要があります理解してJSONに変換します。 Questionは、既存の配列を互換性のある配列に変換して、必要な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

あなたはこの1つのだけの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

あなたの答えは完璧に動作しています。あなたのコードを見てください。私はこの種のコードを書くためにどのようにレベルに達することができるのだろうかと思います。もう一度おねがいしますmr @brevis –

関連する問題