简体   繁体   中英

generate json format using php

I want to generate .json file format in php file. for that i write following code.

<?php
$res=array();
$response = array();
$con=mysql_connect("localhost","root","");
if(!$con){
die("connection failed".mysql_error());
}
$db=mysql_select_db("companies",$con);
if(!$db){
die("connection failed".mysql_error());
}
$result = mysql_query("SELECT * FROM companies");

while($row = mysql_fetch_array($result))  {
 $res[]=array('name'=> $row['name'],'id' => $row['company_id']+1);
}
mysql_close($con);
$response['company'] = $res;
echo (json_encode($response));
?> 

it gives output like this:

{"company":[{"name":"abc","id":2},{"name":"cde","id":3}]} 

but i want output like this:

[{"company":{"name":"abc","id":1}},{"company":{"name":"cde","id":2}}]

how should i change my php file?

You need one more associative array:

while($row = mysql_fetch_array($result))  {
    $res[] = array(
        'company' => array('name'=> $row['name'],'id' => $row['company_id']+1) 
    );
}

And now all you have to send is json encoded $res .

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