1

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

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

thank u @Machavity, it worked. what if there are multiple items with same key??
If they have the same key it will overwrite. You'll have to ask a separate question with a better explanation of what you want there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.