简体   繁体   中英

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!

EDIT

$myjson = array();
    while($row = pg_fetch_array($result)) {
        $json = array(
            'contact_firstname' => addslashes($row['contact_firstname']),
            'contact_lastname'  => addslashes($row['contact_lastname']),
            'contact_id'        => addslashes($row['contact_id']),
            'contact_email'     => explode(',,,', addslashes($row['contact_email']))
        );
        array_push($myjson, $json);
    }

    echo json_encode($myjson);

That's invalid json (the keys must use double quotes). My advice: just create nested PHP arrays (and/or objects), then encode in one go with json_encode . This way you'll also avoid other problems, like escaping newlines inside your strings.

For example:

$some_data = array(
    'something' => 10,
    'something_else' => "foo",
    'some_array' => array(1,2,3,4)
);
echo json_encode($some_data);

Output:

{"something":10,"something_else":"foo","some_array":[1,2,3,4]}

Build an array with your data, and then pass the arry into json_encode , you will get a nicely formatted string.

$BigArray = array();
$Index = 0;

while($row = getSomeData()){

    $BigArray[$Index] = array(
        'Name'    => $row['name'],
        'Age'     => $row['age'],
        'Colors'  => array(
            '0'        => 'Red',
            '1'        => 'Blue'
        )
    );

    $Index++;

}

echo json_encode($array);

{"Name":"Matt","Age":"20","Colors":["Red","Blue"]}

EDIT

More efficient way (I think, less data anyway...)

$Names = array();
$Ages = array();
$Colors = array();

$Index = 0;

while($row = getSomeData()){

    $Names[$Index] = $row['name'];
    $Ages[$Index] = $row['age'];
    $Colors[$Index] = array(
        '0',    => 'Red',
        '1',    => 'Blue'
    };

    $Index++;

}

$JSonArray = array(
    'Names'    => $Names,
    'Age'      => $Ages,
    'Color'    => $Colors
);

json_encode($JSonArray);

The difference here will be that you will name have a name valued pair for each object in your array:

Name: Matt Age: 20, Name: Jason, Age: 24

You will have an array of names.

Names: Matt, Jason, Eric
Ages: 20, 24, 26

Just create a native PHP object and use json_encode :

json_encode($obj);

So instead of this:

$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;

You only need this:

echo json_encode($result);

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