1

I am having trouble with ids in an associative array not being encoded in the JSON string. I have the following PHP snippet:

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

Which correctly produces the following json result:

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

But if I do it manually like this:

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

I get:

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

So I'm wondering why in the second case the IDs are not "displayed" as it would in an associative array. Instead just a list appears. This despite the fact that I enter the IDs as strings and not as integers.

Any help would be appreciated.

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
MirrorMirror
  • 186
  • 8
  • 36
  • 70
  • 2
    Just because you manually set the correct automatic IDs for an array. Change the second to other number, or start from another number different to zero and you will see. – user3153340 Aug 26 '19 at 08:49
  • 2
    That's because at the first example you don't use sequential keys 1,3... , but the second one you used a sequential keys 0 then 1. So if you want to force the the array to be an object you can use `JSON_FORCE_OBJECT` instead of `JSON_PRETTY_PRINT`. – abdallah Nofal Aug 26 '19 at 08:55

0 Answers0