Skip to content
Advertisement

Create Json array from mysql data

I need a bit of help, i have this code:

$arr = [
        "inventory_id" => 2937,
        "products" => [],
];
$q = $dbc->query("SELECT quantity,productId FROM `Products` LIMIT 1");

while ($rs = $q->fetch_assoc()) {
    $arr['products'][] =  [$rs['productId']  => ["bl_3369" => $rs['quantity'] ] ];

}

which is returning

{
   "inventory_id":2937,
   "products":[
      {
         "154801353":{
            "bl_3369":"10"
         }
      }
   ]
}

and i need to return like this:

{
    "inventory_id": "2937",
    "products": {
        "154801353": {
            "bl_3369": "10"
        }
    }
}

Could someone helping me? I search everywhere but i don’t see how to adjust array to get needed structure

Advertisement

Answer

You’re adding an extra array layer with the []. Change the code to this:

while ($rs = $q->fetch_assoc()) {
    $arr['products'][$rs['productId']] =  ["bl_3369" => $rs['quantity']];
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement