如何从 mysqli while 输出 json 数组

问题描述 投票:0回答:1

我需要此代码的帮助

$token = $_POST['token'];
$get_data = mysqli_query($db_con,"SELECT * FROM `app_login` WHERE `token`='$token'");
while ($d_token_data = mysqli_fetch_array($get_data)){
    $code = $d_token_data['code'];
    $get_acc_data = mysqli_query($db_con,"SELECT * FROM `students` WHERE `login_code`='$code'");
    $d_get_data = mysqli_fetch_all($get_acc_data,MYSQLI_ASSOC);
    echo json_encode(array('status' => '1' , 'data' => $d_get_data));
}

我得到了多行的信息

多行

单排

单排

我也尝试过 全部

$token = $_POST['token'];
$get_data = mysqli_query($db_con,"SELECT * FROM `app_login` WHERE `token`='$token'");
$d_token_data = mysqli_fetch_all($get_data,MYSQLI_ASSOC);
$code = $d_token_data['code'];
$get_acc_data = mysqli_query($db_con,"SELECT * FROM `students` WHERE `login_code`='$code'");
$d_get_data = mysqli_fetch_all($get_acc_data,MYSQLI_ASSOC);
echo json_encode(array('status' => '1' , 'data' => $d_get_data));
php arrays json api mysqli
1个回答
0
投票
$token = $_POST['token'];
$get_data = mysqli_query($db_con,"SELECT * FROM `app_login` WHERE `token`='$token'");
$dataToReturn = [];
while ($d_token_data = mysqli_fetch_array($get_data)){
    $code = $d_token_data['code'];
    $get_acc_data = mysqli_query($db_con,"SELECT * FROM `students` WHERE `login_code`='$code'");
    $d_get_data = mysqli_fetch_all($get_acc_data,MYSQLI_ASSOC);
    $dataToReturn[] = $d_get_data;
}
echo json_encode(array('status' => '1' , 'data' => $dataToReturn));

您应该先准备数据,然后只返回一次数据。

© www.soinside.com 2019 - 2024. All rights reserved.