2016-12-28 28 views
2

在PHP中,我需要下面的圖片CSV文件轉換成數組格式:閱讀csv格式的類別和子類別,並準備多維數組

此代碼創建類別和子類別。如果客戶將添加額外的類別和子類別,則需要按照該類別工作。所以我需要動態的。

enter image description here

Array格式:

Array 
(
    [0] => Cateory1 
    [Cateory1] => Array 
     (
      [0] => SubCategory11 
      [1] => SubCategory12 
      [2] => SubCategory13 
      [3] => SubCategory14 
     ) 

    [1] => Cateory2 
    [Cateory2] => Array 
     (
      [0] => SubCategory21 
      [1] => SubCategory22 
      [2] => SubCategory23 
       [SubCategory23] => Array 
       (
        [0] => SubCategory221 
        [1] => SubCategory222 
       ) 
      [3] => SubCategory24 
     ) 

    [2] => Cateory3 
    [Cateory3] => Array 
     (
      [0] => SubCategory31 
      [1] => SubCategory32 
      [2] => SubCategory33 
     ) 

    [3] => Cateory4 
    [Cateory4] => Array 
     (
      [0] => SubCategory41 
      [SubCategory41] => Array 
      (
       [0] => SubCategory411 
       [SubCategory411] => Array 
       (
        [0] => SubCategory4111 
        [SubCategory4111] => Array 
        (
         [0] => SubCategory41111 
        ) 
       ) 
      ) 
     ) 
) 

請幫助我實現這一個。

謝謝。

+0

您能否提供您的csv文件中的內容? –

+0

https://i.stack.imgur.com/BcIfW.png客戶端提供了示例格式。 (在這個問題中附加csv圖片)。 –

+0

我的意思是原始數據,而不是圖像,因爲那是什麼相關,iquess,或者你是否試圖使用OCR檢測值? –

回答

1

雖然我同意Pitchinnate,但我有一些空閒時間,我討厭解析那種csv垃圾,所以我想我試試看。這是一段可能讓你去的代碼。我沒有測試或優化任何東西,所以如果這不能如預期的那樣工作,它可能仍然指向正確的方向。

// I assume, $imput is a twodimensional array containing the csv data 

// the multi dimensional result array 
$result = array(); 

// accumulated categories of current-1 line 
$lastCat = array(); 
foreach($input as $line) { 
    // accumulated categories of current line 
    $cat = array(); 



    //First we create an array in $cat that contains the full "breadcrumbs" per line e.g. 
    // ['category1', 'SubCategory11', 'SubCategory114', ...] 
    $marker = PHP_INT_MAX; 
    for ($i=0; $i<count($line); $i++) { 
     if ($marker < $i) { 
      $cat[$i] = ''; 
     } else if ($line[$i] != '') { 
      $cat[$i] = $line[$i]; 
      $marker = $i; 
     } 
    } 

    // then using these category breadcrumbs, we create the result arrays 
    // you could do this using recursion if you want 
    $tmp = $result; 
    for ($i=0; $i<count($cat); $i++) { 
     // if we haven't seen this category yet, create it 
     // a bit bulky, but necessary as you want the categories with numeric indices as well 
     if (!isset($lastCat[$i]) || $cat[$i] != $lastCat[]) { 
      $tmp[] = $cat[$i]; 
      // Check if there are still subcategories left in this line... 
      if (!empty($cat[$i+1])) { 
       //... and if so, create the category named index if not already existing 
       if (!array_key_exists($cat[$i], $tmp)) { 
        $tmp[$cat[$i]] = array(); 
       } 
       $tmp = $tmp[$cat[$i]]; 
      } else { 
       // ... and if not, we are finished with this line 
       break; 
      } 
     } 
    } 
    $lastCat = $cat; 
}