2016-03-30 89 views
1

我有一個SQL表是這樣的:結合的MySQL列獲得嵌套的JSON結果

id a b c1 c2 c3 d 
1 x y z1 z2 z3 w 
.... 

我想下面的JSON輸出

{ 
"data": { 
    "id": "1", 
    "a": "x", 
    "b": "y", 
    "c": { 
     "c1": "z1", 
     "c2": "z2", 
     "c3": "z4" 
     }, 
    "d": "w" 
    } 
} 

和mysqli查詢如何應該是這種情況?數組格式和循環是什麼應該將查詢結果轉換爲所需的json?

對於新行,它將被添加到數據中。因此,這將成爲 「數據」:{data_of_row1,data_of_row2}

+0

我已經嘗試了一些東西,但他們沒有接近預期的輸出。 – suku

+0

如果你有多於一行的表格,那該怎麼辦? JSON應該是怎樣的? – mitkosoft

+0

@mitkosoft:我添加了json應該查找多行的方法 – suku

回答

1

簡單preg_matchforeach能做到這一點:

<?php 
     $link = mysqli_connect('host', 'user', 'pass', 'db') or die(mysqli_error($link)); 
     $query = "SELECT * FROM sql_table ORDER BY id"; 
     $result = mysqli_query($link, $query) or die(mysqli_error($link)); 
     $json = array(); 
     $rc = 0; 
     while($row = mysqli_fetch_assoc($result)){ 
      foreach($row as $rowName => $rowValue){ 
       if(preg_match_all('/\d+/', $rowName) !== 0){ 
        $index = substr($rowName, 0,1); 
        $json[$rc]['data'][$index][$rowName] = $rowValue; 
       }else{ 
        $json[$rc]['data'][$rowName] = $rowValue; 
       } 
      } 
      $rc++; 
     } 
     print_r(json_encode($json)); 
    ?> 

輸出:

[{ 
    "data": { 
     "id": "1", 
     "a": "x", 
     "b": "y", 
     "c": { 
      "c1": "z1", 
      "c2": "z2", 
      "c3": "z3" 
     }, 
     "d": "w" 
    } 
}, { 
    "data": { 
     "id": "2", 
     "a": "xx", 
     "b": "yy", 
     "c": { 
      "c1": "zz1", 
      "c2": "zz2", 
      "c3": "zz3" 
     }, 
     "d": "ww" 
    } 
}] 

This w生病與任何類似於你的列(f4, f5, r, t等)。

+0

這看起來更像它 – Strawberry

0

可以使CONCAT使用和explode();

$q = $db->prepare("SELECT id, a, b, CONCAT(c1, "|", c2, "|", c3) AS c, d FROM mytable WHERE id = 1"); 
$rows = $q->fetchAll(); 

$data = []; 

foreach($rows as $row){ 
    $explC = explode("|", $row['c']); 

    $cValues = []; 
    foreach($explC as $key => $c){ 
     $cValues["c".($key+1)] = $c; 
    } 

    $data['data'][] = [ 
     "id" => $row['id'], 
     "c" => $cValues 
    } 
} 

echo json_encode($data); 
+0

我不明白前12行代碼。 – Strawberry

+0

你能更具體嗎? – Daan