组合mysql列以获取嵌套的json结果

时间:2016-03-30 11:48:18

标签: php mysql json

我有一个像这样的SQL表:

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}

2 个答案:

答案 0 :(得分:1)

使用preg_match的简单foreach可以做到这一点:

    <?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"
    }
}]

这适用于与您类似的任何列(f4, f5, r, t等)。

答案 1 :(得分:0)

您可以使用CONCATexplode();

$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);