2015-01-04 4 views
-2

어떻게 결국 다음 코드를 테이블 또는 볼 수있는 형식으로 만들 수 있습니까?JSON이 테이블을 생성하기 위해 인코딩합니다.

$query = 
    "SELECT title, descr FROM details"; 

$result = mysqli_query($connection,$query); 

$details = array(); 
while ($row = mysqli_fetch_assoc($result)) { 
    array_push($details, $row); 
} 

echo json_encode($details); 
+0

json이 필요하지 않습니다. 그렇습니까? 행을 배열로 밀어 넣는 대신 테이블에 에코를 넣지 않으시겠습니까? – JFK

답변

0

JSON 할 필요가 그러나 내가 쉽게 변경을 할 수 있도록 테이블이 구성되는 방법을 지시하기 위해 JSON 템플릿 파일을 만들기 위해 같은 테이블을 만들기로, 그 결과를 인코딩합니다.

// this would normally be located elsewhere. 
$templateJson = '"columns": { 

    "title":{ 
     "title": "Title", 
     "class": "title" 
    }, 
    "descr":{ 
     "title": "Description", 
     "class": "descr" 
    } 
}'; 

$template = json_decode($templateJson); 

if(is_array($details)) 
{ 
    $markup = "<table><thead><tr>"; 

    foreach($template["columns"] as $col=>$format) 
    { 
     $markup .= '<th class="'.$format['class'].'">'; 
     $markup .= $format['title']; 
     $markup .= '</th>'; 
    } 

    $markup .= "</tr></thead><tbody>"; 

    foreach($details as $i=>$row) 
    { 
     $markup .= '<tr>'; 
     foreach($template as $col=>$format) 
     { 
      $markup .= '<td>'.$row[$col].'</td>'; 
     } 
     $markup .= '</tr>'; 
    } 

    $markup .= "</tbody></table>"; 
} 

echo $markup; 

내가하는 것보다 더 많은 루프를하는 경향이 있지만, 더 좋은 방법이있을 수 있지만 유효한 테이블 마크 업을 제공합니다.

관련 문제