Wednesday, 2 October 2013

php dynamically generate json

php dynamically generate json

i am trying to combine AngularJS with a php backend. Right now i am trying
to generate a json with php to return it to a http request to angular. So
far i created this php.
$dbhost = "localhost";
$dbport = "5432";
$dbname = "fixevents";
$dbuser = "postgres";
$dbpass = "123";
$connect = pg_connect("host=" . $dbhost . " port=" . $dbport . " dbname="
. $dbname . " user=" . $dbuser . " password=" . $dbpass);
$query = "SELECT contact_firstname, contact_lastname, contact_id,
contact_email FROM contact WHERE user_id = 1";
$result = pg_query($connect, $query);
$comma = '';
$json = '[';
while ($row = pg_fetch_array($result)) {
$json .= $comma . '{';
$json .= 'contact_firstname:"' . addslashes($row['contact_firstname'])
. '",';
$json .= 'contact_lastname:"' . addslashes($row['contact_lastname']) .
'",';
$json .= 'contact_id:' . addslashes($row['contact_id']) . ',';
$json .= 'contact_email:[';
$contact_email = explode(',,,', addslashes($row['contact_email']));
$comma_email = '';
foreach($contact_email as $email) {
$json .= $comma_email . '"' . $email . '"';
$comma_email = ',';
}
$json .= ']';
$json .= '}';
$comma = ',';
}
$json .= ']';
echo $json;
But i read some comments by greater minds than mine :) and they said
creating the json manually is not the best idea. Can anyone tlel me how to
generate this json is a more stylish way? I saw something about
json_endode and array but i dont know how to add a list inside a list. I
have a list and inside each list item i have another list with emails
because 1 contact can have more emails. My generated JSON right now looks
like this
[{contact_firstname:"Daniel",contact_lastname:"Pacuraru",contact_id:1,contact_email:["pacurarudaniel@gmail.com","hello@pacurarudaniel.com"]},{contact_firstname:"Someone",contact_lastname:"Else",contact_id:2,contact_email:["someone.else@gmail.com"]}]
Thank you, Daniel!

No comments:

Post a Comment