Mary Reejo R asked this 3 months ago

How to get nested json

I created a json with PHP code as shown below

PHP code:

while($row1=$check1->fetch_assoc())
{
$empleadresult['empname']=$row['empname'];
$empleadresult['empemailid']=$row1['empemailid'];
$CheckSql2 = "SELECT * FROM leadservices,services WHERE leadservices.leadslno='$leadsl'";
$check2=$con->query($CheckSql2);
while($row2 =$check2->fetch_assoc())
{
 $output2[] = array("service_id" => 
 $row2['service_id'],"service_name" => 
 $row2['service_name']);
}
$empleadresult['services']=$output2;
$leadarray[] = $empleadresult;
$trimmed['LeadDetailsObject'] = str_replace('\r\n','', $eadarray);
echo json_encode($trimmed,JSON_UNESCAPED_SLASHES);

output of above code is

{
  "LeadDetailsObject":[
	{
		"empname": "Anuj Sharma",
		"empemailid": "anuj@toplinebiz.com",
		"service": [
		   {
			"service_id": "6",
			"service_name": "Landscaping And Gardening"
		   },
		   {
			"service_id": "2",
			"service_name": "Civil Finishing And Tumkey Civil Projects"
		   }
		]
      }
  ]
}

from this output how to remove ssquare brackets inside the json (ie,after service)and display {} in the place of [].


Best Answer by Noel 3 months ago

Call str_replace() function on the output of json_encode function.


$square = array("[", "]");
$curly = array("{", "}");
str_replace($square, $curly, json_encode($trimmed,JSON_UNESCAPED_SLASHES));

Hope this helps.