首页 > 解决方案 > MySQLI 查询结果(多行)到 PHP 中的 JSON

问题描述

我无法使用 JSON_encode() php 函数查看我的 mysql 查询结果的所有行作为 JSON 对象返回。这是我的代码:

$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne = array();
$bilan = array();

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID']
    );
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

它返回我:

{"":null,"0":{"User_ID":"1"},"1":{"User_ID":"19"},"2":{"User_ID":"78"},"3 ":{"User_ID":"79"},"4":{"User_ID":"85"},"5":{"User_ID":"86"},"6":{"User_ID":" 87"},"7":{"User_ID":"88"},"8":{"User_ID":"91"},"9":{"User_ID":"92"},"10": {"User_ID":"93"},"11":{"User_ID":"94"},"12":{"User_ID":"95"},"13":{"User_ID":"96" },"14":{"User_ID":"97"},"15":{"User_ID":"98"},"16":{"User_ID":"99"},"17":{"User_ID":"100"},"18":{"User_ID":"101"},"19":{"User_ID":"102" },"20":{"User_ID":"103"},"21":{"User_ID":"104"},"22":{"User_ID":"105"},"23":{" User_ID":"106"},"24":{"User_ID":"107"},"25":{"User_ID":"108"},"26":{"User_ID":"109"}, "27":{"User_ID":"110"},"28":{"User_ID":"111"},"29":{"User_ID":"112"},"30":{"User_ID" :"113"},"31":{"User_ID":"114"},"32":{"用户 ID":"115"},"33":{"用户 ID":"116"}}

现在,我试图在 json 输出中关联每条记录的其他字段。但是当把这个添加到我的代码中时,就没有更多的输出了。

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );      
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ][
        ['User_Nom'][$rowr['User_Nom']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

似乎可以显示数值而不是字母字符。

请帮助我在相同的输出中混合数字和 alpha 内容。

谢谢阿诺

标签: phpmysqljsonassociative-array

解决方案


为了清楚起见,转换为 PHP >= 5.5。

我在猜测和假设,但我还能做什么?我看到的主要问题是您可能会因数组语法而绊倒。看来您想通过“User_ID”重新索引结果,我假设这是在每个表记录中找到的一些字符串标识符。

模块化,程序形式...

/*
    Assuming you are attempting to re-index by the 'User_ID' field
    of each record before encoding as JSON.
*/

function getDb($ip, $user, $password, $database) {
    $db = mysqli_connect($ip, $user, $password, $database);

    //error checking etc ...

    return $db;
}

function selectRecords(mysqli $db, $sql) {
    $result = mysqli_query($db, $sql);

    if (!$result) {
        throw new UnexpectedValueException("Database query (read) was unsuccessful!");
    }

    return $result;
}

function getUserRecords(mysqli $db) {
    $query = 'SELECT * FROM Users';
    return selectRecords($db, $query);
}

function reindexByField($newIndex, $userResults) {
    $reindexed = [];

    while ($row = mysqli_fetch_assoc($userResults)) {
        if (!isset($row[$newInded])) {
            throw new OutofBoundsException("The index '" . $newIndex . "' does not exist in the tested record");
        }

        $redindexed[$row[$newIndex]] = $row;
    }

    return $reindexed;
}

function getJsonFromArray(array $records) {
    $json = json_encode($records, JSON_FORCE_OBJECT);

    if (!$json) {
        throw new UnexpectedValueException("Records were not encoded into a JSON formatted string. Got boolean false, instead.");
    }

    return $json;
}

在程序形式中,然后...

try {
    $db = getDb($ip, $user, $password, $db); // Just pretend for a moment.
    echo getJsonFromArray(reindexByField('User_ID', getUserRecords($db));
} catch (e) {
    // Your handler code here.
} finally {
    mysqli_close($db);
}

面向对象的方法可以使您的代码更有条理。


推荐阅读