JSON object creation using PHP - from fetched values of database columns -


i new php. working on project of recommendation system.

here fetching values database "userid" , "items".

and, want create json object this

{     "john": ["a", "b", "c", "d", "e"],     "alex": ["a", "b", "x", "y", "z"],     "me": ["a", "b", "c", "f", "r"] } 

but getting

[     {         "john": ["a", "b", "c", "d", "e"],     },     {         "alex": ["a", "b", "x", "y", "z"],     },     {         "me": ["a", "b", "c", "f", "r"]     }  ] 

this code have tried,

<?php      include "init.php";//database connection      $sql = "select * orders";      $result = mysqli_query($connection,$sql);          while($row = mysqli_fetch_assoc($result)){             $userid = $row['userid'];             $items = $row['items'];             $itemsarray = explode(',', $items);              if(!in_array($userid, array_keys($user_item))){                 $user_item[$userid] = $itemsarray;             }             else{                  $values = $user_item[$userid];                  $arr = array_merge($values,$itemsarray);                  $user_item[$userid] = $arr;            }         }     echo json_encode($user_item); ?> 

you need have key on top level set. otherwise php convert json array. replace

$arr = [$userid => $itemsarray]; array_push($user_item, $arr); 

with

$user_item[$userid] = $itemsarray; 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -