2017-06-06 106 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