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

如何将php数组转换为json字符串?,php,arrays,json,string,encode,Php,Arrays,Json,String,Encode,我正在尝试将php数组转换为json字符串: $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 {

我正在尝试将php数组转换为json字符串:

$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);
这将返回一个数组:

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
        )

)
如果我对它进行json编码,我会得到一个json字符串,开头和结尾都是“[”。我如何克服这个问题?我希望json字符串看起来像这样

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

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

如果您不希望在这种情况下使用修剪,只需移除这些方括号:

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

您正在序列化一个数组,因此您的结果非常好,因为json数组在[]中表示

如果希望将每个对象单独表示为json,请执行以下操作:

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

如果删除
[
]
就不再是
json
(没有解析器能够对其进行解码)您有一个包含一个关联数组的数组。如果希望返回单个json对象,则需要指定哪个
$row
。在该完整数组上运行
json\u encode
将不会返回上面提供的json输出。因此,您在此处省略了一些信息。可能存在重复的