首页 > 解决方案 > PHP函数:将数组编码为JSON格式而不带大括号

问题描述

如何将数组编码为 JSON 格式而不获取左大括号{并以右大括号结尾}

当我使用下面的函数时,我得到错误:

JSONException:java.lang.String 类型的值无法转换为 JSONObject

在我的 Android 应用程序中。所以我无法从我的数据库中获取列表视图。

public function View()
{
    $con=$this->connect();
    if($con != null)
    {
        $result=$con->query(Constants::$SQL_SELECT_ALL);
        if($result->num_rows > 0)
        {
            $items_list=array();
            while($row=$result->fetch_array())
            {
                array_push($items_list, array("id"=>$row['id'],"item_name"=>$row['item_name'],"item_description"=>$row['item_description'],"item_image_url"=>$row['item_image_url']));
            }
            print(json_encode(array_reverse($items_list)));
        }else
        {
        }
        $con->close();

    }else{
        print(json_encode(array("PHP EXCEPTION : CAN'T CONNECT TO MYSQL. NULL CONNECTION.")));
    }
}
public function handleRequest() {
    if (isset($_POST['name'])) {
        $this->insert();
    } else{
        $this->select();
    }
}
}

知道我该怎么做吗?

标签: phpjson

解决方案


您可以使用 ltrim,检查一下,看看是否适合您 :)

ltrim - 从字符串的开头去除空格(或其他字符),更多信息在这里

$array = array('id' => 123, 'item_name' => 'Some example', 'item_description' => 'Another example');

$json =  json_encode($array);

echo ltrim($json, '{');

结果字符串是

"id":123,"item_name":"Some example","item_description":"Another example"}

推荐阅读