简体   繁体   中英

How to create nested json from mysql tables in PHP

**I have created two tables in the mysql 1st table is cat_names, id and the 2nd table is Qoutes, id iam retriving from php script but i want nested

I have got like this when exiecuted**

[{"cat_names":"Animal","Qoutes":"this is id 1st text"},{"cat_names":"Animal","Qoutes":"this is 1st id text"},{"cat_names":"ball","Qoutes":"this is 2nd id text"},{"cat_names":"ball","Qoutes":"this is 2nd id text"},{"cat_names":"cat","Qoutes":"this is 3rd id text"},{"cat_names":"cat","Qoutes":"this is 3rd id text"}]

Code :

$host = 'localhost';
$user = 'root';
$pwd = 'root';
$db = 'demoqouteapp';

$conn = mysqli_connect( $host,$user,$pwd,$db);

if( !$conn ) {
   die ("Error in connection:" . mysqli_connect_error());
}

$response = array();

$sql_query = "select c.cat_names, q.Qoutes from categories AS c inner join `qoute` as q on c.id = q.id";

$result = mysqli_query( $conn, $sql_query );

if(mysqli_num_rows($result)> 0) {

    while($row = mysqli_fetch_assoc($result)) {
        array_push($response,$row);
    }
} else {

    $response['success'] = 0;
    $response['message'] = 'No data';
}

echo json_encode($response);
mysqli_close($conn);        

I want cat_names in an array and quotes is also in array-like

[{
        "cat_names": "animals",
        "qoutes":  [{
                       "qoutes": "this is 1 st qoute"
                    },
                    {
                       "qoutes": "this is 1 st qoute"
                    }]
 }]

You want to group the data from several records into one object here - and that is something you need to do yourself.

This is easiest, if you use the category as associative array key first:

while($row = mysqli_fetch_assoc($result)) {
  if(!isset($response[$row['cat_names']])) {
    $response[$row['cat_names']] = [
      'cat_names' => $row['cat_names'],
      'qoutes' => []
    ];
  }
  $response[$row['cat_names']]['qoutes'][] = ['qoutes' => $row['Qoutes']];
}

If $response[$row['cat_names']] is not set yet, that means we are dealing with the first record with a particular cat name. In that case, we initialize $response[$row['cat_names']] as a new array, and set the cat_names in that, and initialize qoutes as an empty sub-array.

After that, the current quote (I assume you actually mean that you have quotes here, so maybe fix the spelling now, before that gets a hassle later …) gets pushed into the qoutes sub-array.

Now we just need to get rid of the associative index on the outer level again - otherwise, encoding this as JSON would give you an object, not an array. This can easily be done using array_values , so after your loop you put:

$response = array_values($response);
echo json_encode($response);

… and you should have what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM