2

I have a sql table like this:

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

I want the following json output

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

How should the mysqli query be for this case? What should be the array format and looping be to convert the query result into the required json?

For a new row, it would be added to data. So it would become "data": {data_of_row1, data_of_row2}

9
  • I have tried a few things but they were no where near the expected output. Commented Mar 30, 2016 at 12:02
  • what about if you have more than one row into the table? how the JSON should looks like? Commented Mar 30, 2016 at 12:11
  • @mitkosoft: I have added the added how the json should look for multiple rows Commented Mar 30, 2016 at 12:24
  • What's wrong with json_encode? Commented Mar 30, 2016 at 12:28
  • @Strawberry, I want the sql query and looping to get an array which on json_encode would give the following result Commented Mar 30, 2016 at 12:31

2 Answers 2

1

Simple preg_match with foreach can do that:

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

Output:

[{
    "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 will work with any columns similar to yours (f4, f5, r, t etc).

Sign up to request clarification or add additional context in comments.

4 Comments

This looks more like it
Does that code need to be expanded if the data are more deeply nested? Is there a generic version?
@MawgsaysreinstateMonica, most probably it should be expanded, as it depends on the name of the table's columns. So we might need an example of how your data is nested and what you want as output, best in a new SO post.
For the time being, I am examining MySql v8's new JSON functionality. E.g mysqlserverteam.com/json_table-the-best-of-both-worlds
0

You can make use of CONCAT and 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);

1 Comment

Could you be more specific?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.