Cooolranjan Cooolranjan - 6 months ago 15
JSON Question

how to attach subject in json data

i want to attach the subject in json data. so, i can fetch using $.each(data.subject). below is my api code where i am fetching all the data encoding into json format. any help would be appreciated.

[{"id":"79","FirstName":"Elon","MiddleName":"","LastName":"Musk","Gender":"Male","Location":"New York","Email":"elonmusk@tesla.com","Mobile":"1234567890"}]


and want to receive like this:

{ "personaldetails":[{"id":"79","FirstName":"Elon","MiddleName":"","LastName":"Musk","Gender":"Male","Location":"New York","Email":"elonmusk@tesla.com","Mobile":"1234567890"}


this is my code;

$personal = $db->prepare('select Id,FirstName,MiddleName,LastName,Gender,Location,Email,Mobile from personaldetails ORDER BY Id DESC');
$personal->execute();
$json_data=array();



foreach($personal as $row)//foreach loop
{

$json_array['id']=$row['Id'];
$json_array['FirstName']=$row['FirstName'];
$json_array['MiddleName']=$row['MiddleName'];
$json_array['LastName']=$row['LastName'];
$json_array['Gender']=$row['Gender'];
$json_array['Location']=$row['Location'];
$json_array['Email']=$row['Email'];
$json_array['Mobile']=$row['Mobile'];
array_push($json_data,$json_array);

}
$books = $db->prepare('select UserId,BookTitle,BookGenre,BookWriter,BookDescription from bookdetails ORDER BY UserId Desc');
$books->execute();
$json_data1=array();

//$bookNo = 0;
foreach($books as $row)//foreach loop
{
//$bookNo++;
//$json_array1['BookNo']= $bookNo;
$json_array1['UserId']=$row['UserId'];
$json_array1['BookTitle']=$row['BookTitle'];
$json_array1['BookGenre']=$row['BookGenre'];
$json_array1['BookWriter']=$row['BookWriter'];
$json_array1['BookDescription']=$row['BookDescription'];

//here pushing the values in to an array
array_push($json_data1,$json_array1);

}
header('Content-type: application/json');
echo json_encode($json_data);
echo json_encode($json_data1);
//echo json_encode($json_data1);

?>


thanks in advance

Answer

Simple!

echo json_encode(array("yourSubject"=>$responseArray));

Here you can also define some other data with yourSubject like

code: response_code, success: true/false

for example

echo json_encode(array(
                  "yourSubject"=>$responseArray,
                  "success" => true,
                  "code" => 200,
                  "otherinfo" => "somedata"
      ));

that will gevi you json response like:

{
     "yourSubject": [{}],
      "success" : true,
      "code" : 200,
      "otherinfo" : "somedata"

}

in front end if this is your data object you can easily access data

with data.code, data.yourSubject and so on.

Comments