REHAN SHIKKALGAR REHAN SHIKKALGAR - 22 days ago 6
JSON Question

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

I am new to PHP.
I am working on project of recommendation system.

here i am fetching values from database like "userid" and "items".

and, I want to create JSON object like this

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


but what i am getting is

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

]


this is the code what i have tried,

<?php

include "init.php";//database connection

$sql = "select * from Orders";

$result = mysqli_query($connection,$sql);

$user_item = [];

while($row = mysqli_fetch_assoc($result)){

//userid
//userid is like "john"
$userid = $row['userid'];

//items
//items are like "a,b,c,d,e"
$items = $row['items'];
//split items on ','
$itemsarray = explode(',', $items);
$arr = [$userid => $itemsarray];
array_push($user_item, $arr);

}
echo json_encode($user_item);
?>

Answer

You need to have the key on the top level set. Otherwise PHP will convert it into a JSON array. Replace

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

with

$user_item[$userid] = $itemsarray;
Comments