我有一个mysqli查询,需要将其格式化为移动应用程序的JSON.

我已经设法为查询结果生成了一个XML文档,但是我正在寻找更轻量级的东西.(有关我当前的XML代码,请参见下文)

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);

// create xml format
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) : 

    $occ = $doc->createElement('data');  
    $occ = $root->appendChild($occ);  

    $child = $doc->createElement('section');  
    $child = $occ->appendChild($child);  
    $value = $doc->createTextNode($title);  
    $value = $child->appendChild($value);  

endwhile;

$xml_string = $doc->saveXML();  

header('Content-Type: application/xml; charset=ISO-8859-1');

// output xml jQuery ready

echo $xml_string;

推荐答案

$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {

    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}

$result->close();
$mysqli->close();
  1. $row = $result->fetch_array(MYSQLI_ASSOC)
  2. $myArray[] = $row

output like this:

[
    {"id":"31","name":"pruduct_name1","price":"98"},
    {"id":"30","name":"pruduct_name2","price":"23"}
]

If you want another style, you can try this:

  1. $row = $result->fetch_row()
  2. $myArray[] = $row

output will like this:

[
    ["31","pruduct_name1","98"],
    ["30","pruduct_name2","23"]
]

Json相关问答推荐

将JSON输入子数组转换为字符串顺序列表输出

将数组中的值作为键连接到另一个数组中的值(Jolt)

在Reaction中从JSON文件中筛选数组

如何避免解析 ISuperObject 类型字段中的 json 对象

如何使用 JOLT 使用输入数组中的值和层次 struct 中的其他字段创建数组

如何强制仅有一个元素的数组在JSON中生成方括号

带有 API 测试的 Typescript JSON 模式验证

取消嵌套数组并将数组名称添加为附加字段

在 NX 工作区中跨多个应用共享 ngx-translate 翻译文件

颠簸转换问题

在循环中将变量添加到 bash 数组

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

N1QL 聚合查询 Couchbase

Spring MVC 4:application/json内容类型设置不正确

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

Spring Security 和 JSON 身份验证

在 .NET 中缩小缩进的 JSON 字符串

将多个值存储在json中的单个键中

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象