2017-06-06 80 views
0

我正在解析HTML並獲取多維輸出數組作爲json。 我解析HTML像我想但我不能創建JSON數組。解析HTML到多維JSON數組

示例輸出foreach循環的:

PS:每JSON對象具有不同的字符串值。

0: 「blahblah」

1: 「blahblah」

2: 「blahblah」

3: 「blahblah」

4:」「//僅空間

5:「blahblah」

6:「blahblah」

7: 「blahblah」

8: 「blahblah」

9:」「//只有空間

...

我想創建JSON數組是這樣的:enter image description here

$output = array(); 
    $html = str_get_html($ret); 

    $lessons["lesson"] =array(); 
    foreach($html->find('table//tbody//tr') as $element) { 

     $temp = strip_tags($element->innertext); 

     array_push($lessons['lesson'], $temp); // the objects (I wrote as 'blahblah' every object but I getting different values always) 

     if($temp == " ") // if there is only space push array the output and create new array 
     { 

      array_push($output , $lessons["lesson"]); 
      unset($lessons); 
      $lessons["lesson"] = array(); 
     } 
    } 
echo (json_encode($output ,JSON_UNESCAPED_UNICODE)); // $output show nothing 

謝謝你的建議。

回答

2

如果你的問題是得到所有的數組,然後下面會讓你在那裏。我沒有很好地遵守代碼,但試圖在評論中解釋我的想法。

$json = ["blahblah" 
,"blahblah" 
,"blahblah" 
,"blahblah" 
," " 
,"blahblah" 
,"blahblah" 
,"blahblah" 
,"blahblah" 
," "]; 


$lessons["lesson"] = []; // I think this is the array you are using 
$tmp = []; // Something tmp to hold things 
foreach($json as $elm){ //Loop what I assume $html->find('table//tbody//tr') is returning 
    if($elm != ' '){//Wait for a ' ' and add to tmp 
     $tmp[] = $elm; 
    } else { 
     $lessons["lesson"][] = $tmp; // This array is done so keep it and restart 
     $tmp = []; 
    } 
} 
+0

謝謝!我改變你的if子句爲「if($ elm!=' ')然後它工作!如果你更新你的文章是這樣的,我會接受你的回答 – pseudocode

+0

@pseudocode完成! – nerdlyist