Raja Gopal Raja Gopal - 2 months ago 8
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'];

$data->subject_name=$subject_name;

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

$data->units=$emparray;
}

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

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

$sql    = "select * from users";

OR

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

PHP CODE

$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'],
            'units'=>array($row)
        )
    );
  }else{
    array_push($data[$res]['units'], $row);
  }
}

echo json_encode($data);

Now you can get your JSON format from above code.