PHP - 从MySQL获取多行并对其进行JSON编码

时间:2017-02-03 07:02:34

标签: php

我试图从JSON数据库中获取MySQL数组。这是获取行并将其添加到数组中的代码部分。

<?php
if($rowcount > 0) {
    while($row = mysqli_fetch_row($fetch)) {
        $row_array["uid"] = $row['unique_id'];
        $row_array["users"]["name"] = $row['name'];
        $row_array["users"]["email"] = $row['email'];
        array_push($users, $row_array);
    }
    mysqli_free_result($fetch);
    echo json_encode($users);
}
?>

此部分导致错误,显示以下消息。

  


                                                                         注意:未定义的索引:unique_id in    /storage/h3/859/644859/public_html/searchfriends.php 在线    20
                                                                         
                                                                         注意:未定义的索引:名称在    /storage/h3/859/644859/public_html/searchfriends.php 在线    21
                                                                         
                                                                         通知:未定义的索引:电子邮件地址    /storage/h3/859/644859/public_html/searchfriends.php 在线    22

每一行代表以下部分。

$row_array["uid"] = $row['unique_id'];
$row_array["users"]["name"] = $row['name'];
$row_array["users"]["email"] = $row['email'];

所以,我相信我没有正确格式化数组。我该如何解决它?

2 个答案:

答案 0 :(得分:2)

基于手册: - http://php.net/manual/en/mysqli-result.fetch-row.php

它会给你一个数字索引数组。所以你必须这样做: -

$row[0],$row[1].... so on

<强> OR

最好应该改变这一行如下: -

while($row = mysqli_fetch_assoc($fetch)) { 
// instead of mysqli_fetch_row use mysqli_fetch_assoc

答案 1 :(得分:1)

<?php
if($rowcount > 0){
    while($row = mysqli_fetch_row($fetch)) {
echo "<pre>";
 print_r($fetch); //  check here you have columns of email ,name etc.. or not
 die;
        $row_array["uid"] = $row['unique_id'];
        $row_array["users"]["name"] = $row['name'];
        $row_array["users"]["email"] = $row['email'];
        array_push($users, $row_array);
    }
    mysqli_free_result($fetch);
    echo json_encode($users);
}
?>