PHP JSON编码不返回数组键

时间:2019-08-26 08:27:03

标签: php json

我遇到了关联数组中的ID未在JSON字符串中编码的麻烦。我有以下PHP代码段:

require_once("../common/connection.php");
$hermesDB_PRST = $HERMESPDO->prepare("SELECT * FROM tblTX INNER JOIN tblUsers ON tblTX.SourceUserID = tblUsers.UserID WHERE TargetUserID = :TargetUserID AND TargetNotified = 0");
$hermesDB_PRST->bindValue(":TargetUserID", "2");                    
$hermesDB_PRST->execute() or die($HERMESPDO->errorInfo());
$NotificationsStack = array();
while ($hermesDB_RSLT = $hermesDB_PRST->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
    $ID = $hermesDB_RSLT["ID"];
    $Source = $hermesDB_RSLT["Source"];
    $Msg = $hermesDB_RSLT["Msg"];
    $Notification = array(
        "TXID" => $ID,
        "Source" => $Source,
        "Msg" => $Msg
    );
    $NotificationsStack[$ID] = $Notification;
}
$sRetData = array(
    "Balance" => 0,
    "Transactions" => $NotificationsStack
);
echo json_encode($sRetData, JSON_PRETTY_PRINT);

可以正确产生以下json结果:

{
    "Balance": 0,
    "Transactions": {
        "1": {
            "TXID": "1",
            "Source": "456",
            "Msg": "reason 1"
        },
        "3": {
            "TXID": "3",
            "Source": "456",
            "Msg": "reason 2"
        }
    }
}

但是,如果我这样手动操作:

$NotificationsStack = array();
$ID = "0";
$Notification = array(
    "ID" => $ID,
    "Source" => "123",
    "Msg" => "haha"
);
$NotificationsStack[$ID] = $Notification;

$ID = "1";
$Notification = array(
    "ID" => $ID,
    "Source" => "456",
    "Msg" => "hehe"
);
$NotificationsStack[$ID] = $Notification;
$sRetData = array(
    "Balance" => 0,
    "Transactions" => $NotificationsStack
);

echo json_encode($sRetData, JSON_PRETTY_PRINT);

我得到:

{
    "Balance": 0,
    "Transactions": [
        {
            "ID": "0",
            "Source": "123",
            "Msg": "haha"
        },
        {
            "ID": "1",
            "Source": "456",
            "Msg": "hehe"
        }
    ]
}

所以我想知道为什么在第二种情况下ID不像在关联数组中那样“显示”。而是仅出现一个列表。尽管我实际上是将ID作为字符串而不是整数输入的。

任何帮助将不胜感激。

0 个答案:

没有答案