使用循环

时间:2016-03-08 00:29:15

标签: php sql json

现在看了一会儿,看起来很简单,但由于某种原因,我无法掌握它。

我的代码目前输出:

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

需要的是:

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

有人能指出我正确的方向吗?我是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);
?>

2 个答案:

答案 0 :(得分:2)

你需要一个二维数组。本质上是一个“阵列阵列”。

有关详细信息,请参阅示例here

$society = array();

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

echo json_encode($society);

答案 1 :(得分:1)

对于您所需的json格式,您需要使用多维数组。并且无需在json_encode()循环中使用while()

示例

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