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