2017-04-20 36 views
0

我試圖將標籤化的格式化的字符串轉換爲一個php數組。我試圖將每個類別轉換成單獨的數組,然後preg_match,但這並沒有太好..任何建議?將標籤化的字符串轉換爲php數組

轉換:

category 1 
    subcategory 1 
     item 1 
     item 2 
    subcategory 2 
     item 1 
     item 2 
    subcategory 3 
     item 1 
     item 2   
category 2 
    subcategory 1 
     item 1 
     item 2 
    subcategory 2 
     item 1 
     item 2   
category 3 
    subcategory 1 
     item 1 
     item 2 
     item 3 
     item 4 

要:

$data = [ 
'category 1' =>[ 
    'subcategory 1' =>[ 
     'item 1', 
     'item 2' 
    ], 
    'subcategory 2' =>[ 
     'item 1', 
     'item 2' 
    ], 
    'subcategory 3' =>[ 
     'item 1', 
     'item 2' 
    ] 
], 
'category 2' =>[ 
    'subcategory 1' =>[ 
     'item 1', 
     'item 2' 
    ], 
    'subcategory 2' =>[ 
     'item 1', 
     'item 2' 
    ] 
], 
'category 3' =>[ 
    'subcategory 1' =>[ 
    'item 1', 
    'item 2', 
    'item 3', 
    'item 4'    
    ] 
] 
]; 

回答

0

好吧,如果你的字符串格式,這裏是一個小解釋功能,可以做到這一點:

function($text){ 
    $arr = []; 
    $category = ""; 
    $subcategory = ""; 
    foreach (explode("\n", $text) as $line) {// For every line 
     if (startsWith($line, ' ')){ 
      if (startsWith($line, '  ')) { 
       // New Item 
       // If it's a new item, you add it inside the current subcategory & category 
       $arr[$category][$subcategory][] = substr($line, 8);// Removes the 8 spaces 
      } 
      else{ 
       // New Subcategory 
       // If it's a new subcategory, you add it as an empty array inside the current category and set $subcategory to the current subcategory 
       $subcategory = substr($line, 4);// Removes the 4 spaces 
       $arr[$category][$subcategory] = []; 
      } 
     } else { 
      // New Category 
      // If it's a new category, you add it as an empty array and set $category to the current category 
      $category = $line; 
      $arr[$category] = []; 
     } 
    } 
    return $arr; 
} 
+0

真棒。工作很好....感謝一堆。 – sam

+0

不客氣 –