简体   繁体   中英

Generating an array of JSON in PHP using a loop

Been looking at this for a while now, it seems simple enough but for some reason I am unable to grasp it.

My code at the moment outputs this:

{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"}
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}

But what I need is this:

[{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}]

Could somebody point me in the right direction please? I'm very new to PHP.

<?php

    $user = 'root';
    $pass = '';
    $db = 'uopuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');


    $statement = mysqli_prepare($con, 'SELECT * FROM society');
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description);

$society = array();

while(mysqli_stmt_fetch($statement)){
    $society['society_id'] = $society_id;
    $society['name'] = $name;
    $society['email'] = $email;
    $society['description'] = $description;
    echo json_encode($society);
}

echo json_encode($society);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

You need a two dimensional array. Essentially an "array of arrays."

See the examples here for more information.

$society = array();

while(mysqli_stmt_fetch($statement)){
    $society[] = array(
        'society_id'  = $society_id,
        'name'        = $name,
        'email'       = $email,
        'description' = $description
    );
}

echo json_encode($society);

For your required json format you need to use multi dimensional array. And no need to use json_encode() inside the while() loop.

Example :

$society = array();
$key = 0;
while(mysqli_stmt_fetch($statement))
{ 
    $society[$key]['society_id'] = $society_id; 
    $society[$key]['name'] = $name;
    $society[$key]['email'] = $email;
    $society[$key]['description'] = $description; 
    $key++;
}
echo json_encode($society); 

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