Home > front end >  Create Json array from mysql data
Create Json array from mysql data

Time:09-23

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

CodePudding user response:

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']];
}
  • Related