dougan4663 2016-05-11 12:34 采纳率: 0%
浏览 82

如何将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"
}]
  • 写回答

2条回答 默认 最新

  • dongshan2680 2016-05-11 12:38
    关注

    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, "]");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊