如何将php数组转换为json字符串?

I am trying to convert a php array to a json string:

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
          $userinfo[] = $row;
    }
    print_r($userinfo);

} else {
    echo "0 results";
}

mysqli_close($conn);

This returns an array:

Array
(
    [0] => Array
        (
            [entity_id] => 24
            [product_name] => Burger
            [product_image_url] => /b/u/burger_large.jpg
            [price] => 234.0000
            [category_id] => 59
        )

    [1] => Array
        (
            [entity_id] => 25
            [product_name] => Massage
            [product_image_url] => /2/9/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg
            [price] => 5000.0000
            [category_id] => 63
        )

    [2] => Array
        (
            [entity_id] => 27
            [product_name] => Chicken Biryani
            [product_image_url] => /b/i/biryani.jpg
            [price] => 500.0000
            [category_id] => 59
        )

    [3] => Array
        (
            [entity_id] => 28
            [product_name] => Panner Chilly
            [product_image_url] => /p/a/panner.jpg
            [price] => 456.0000
            [category_id] => 59
        )

    [4] => Array
        (
            [entity_id] => 31
            [product_name] => Pizza
            [product_image_url] => /p/i/pizza_png7143_1.png
            [price] => 125.0000
            [category_id] => 59
        )

)

if i do json encode on this i get a json string with "[" in the beginning an end. how do i overcome this i want the json string to look like this

{
    "entity_id": "31",
    "product_name": "Pizza",
    "product_image_url": "\/p\/i\/pizza_png7143_1.png",
    "price": "125.0000",
    "category_id": "59"
}

AND NOT LIKE THIS:

[{
    "entity_id": "31",
    "product_name": "Pizza",
    "product_image_url": "\/p\/i\/pizza_png7143_1.png",
    "price": "125.0000",
    "category_id": "59"
}]

If you dont want that square braces in that case using trim just remove those braces:

$user_json = json_encode($userinfo);
$user_json  = trim($user_json, "[");
$user_json  = trim($user_json, "]");

you are serializing an array, so your result is perfectly fine as json-arrays are represented within [].

if you want each object represented as json in isolation, do this:

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
          echo json_encode(row);
    }

} else {
    echo "0 results";
}

mysqli_close($conn);