php - 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();
}
}
}
知道我该怎么做吗?
解决方案
您可以使用 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"}
推荐阅读
- jquery - jQuery document.ready 在 v3.0 之后导致问题
- r - 计算多个回归模型
- r - gganimate 图中的标签行为问题
- javascript - 如何在 Vue.js 中绑定 fontawesome 图标名称
- python - 如何从包含文件名的列表中加载来自 tensorflow 数据管道中不同目录的 .npy 文件?
- php - 基于产品变体数组创建规则数组
- python - 我可以只克隆 Git 存储库中大小低于指定限制的文件吗?
- html - Problem with CSS column-count and first element
- python - Pandas 在 Python 中添加不需要的 0 列
- office-js - Word web 插件:修改上下文菜单不适用于 ExtensionPoint xsi:type="ContextMenu"