Raja Gopal Raja Gopal - 10 months ago 44
JSON Question

Json Response Query

I am now working on getting a Json response from the data in the following table

enter image description here

By using the following Query :

$sql = "select * from subject where subject_name = 'maths'";

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

while($row = mysqli_fetch_array($result))
$data = new stdClass();
$subject_name = $row['subject_name'];
$unit = $row['unit'];
$unit_name = $row['unit_name'];


$emparray[] = array('unit' => $unit,
'unit_name' => $unit_name,


echo json_encode(array($data));

I can get the Json response as :

enter image description here

Now what i want was for overall subjects without using where clause (where subject_name = 'maths')

My required Json o/p is as below :

enter image description here

Answer Source

You can group result by subject_name to your PHP array by following code.

$sql    = "select * from users";


$sql    = "select subject_name,unit,unit_name from users";


$result =  mysqli_query($conn,$sql);
$data   = array();

function search($subject){
  global $data;
  foreach ($data as $key => $value) {
    if (isset($value['subject_name']) && $value['subject_name']==$subject) {
        return $key;
 return false;

while($row = mysqli_fetch_assoc($result)){
  $res = search($row['subject_name']);
  if ($res===false) {
    array_push($data, array(
            'subject_name' =>$row['subject_name'],
    array_push($data[$res]['units'], $row);

echo json_encode($data);

Now you can get your JSON format from above code.