polygoncoin / jsonencode
使用较少资源对大量数据进行PHP JSON编码
v1.0.0
2024-07-01 15:36 UTC
README
使用较少资源对大量数据进行PHP JSON编码
示例
生成作为对象的单行输出。
<?php
require "JsonEncode.php";
// Create JsonEncode Object.
$jsonEncodeObj = JsonEncoder::getObject();
// Execute DB Query
$stmt = $db->select($sql);
$stmt->execute($params);
// For single row - one
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$jsonEncode->encode($row);
// For single row - two
$jsonEncode->startObject();
foreach($stmt->fetch(PDO::FETCH_ASSOC) as $key => $value) {
$jsonEncode->addKeyValue($key, $value);
}
$jsonEncode->endObject();
// Free statement resources and close the cursor.
$stmt->closeCursor();
$jsonEncode = null;
生成作为对象数组的许多行输出。
<?php
require "JsonEncode.php";
// Create JsonEncode Object.
$jsonEncodeObj = JsonEncoder::getObject();
// Execute DB Query
$stmt = $db->select($sql);
$stmt->execute($params);
// For multiple rows
$jsonEncode->startArray();
for(;$row=$stmt->fetch(PDO::FETCH_ASSOC);) {
$jsonEncode->encode($row);
}
$jsonEncode->endArray();
// Free statement resources and close the cursor.
$stmt->closeCursor();
$jsonEncode = null;
在对象内部生成单行输出。
<?php
require "JsonEncode.php";
// Create JsonEncode Object.
$jsonEncodeObj = JsonEncoder::getObject();
// Start JSON object
$jsonEncode->startObject();
// Execute DB Query - 1
$stmt = $db->select($sql);
$stmt->execute($params);
foreach($stmt->fetch(PDO::FETCH_ASSOC) as $key => $value) {
$jsonEncode->addKeyValue($key, $value);
}
// Free statement resources and close the cursor.
$stmt->closeCursor();
// Execute DB Query - 2 (which returns single row)
$stmt = $db->select($sql_2);
$stmt->execute($params_2);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
// Append key / value pair (value can be an integer / string / array)
$jsonEncode->addKeyValue('subCatgories', $row);
// End JSON object
$jsonEncode->endObject();
$jsonEncode = null;
在对象内部生成许多行输出。
<?php
require "JsonEncode.php";
// Create JsonEncode Object.
$jsonEncodeObj = JsonEncoder::getObject();
// Start JSON object
$jsonEncode->startObject();
// Execute DB Query - 1
$stmt = $db->select($sql);
$stmt->execute($params);
foreach($stmt->fetch(PDO::FETCH_ASSOC) as $key => $value) {
$jsonEncode->addKeyValue($key, $value);
}
// Free statement resources and close the cursor.
$stmt->closeCursor();
// Start JSON array inside object
$objectKey = 'subCatgories';
$jsonEncode->startArray($objectKey);
// Execute DB Query - 2
$stmt = $db->select($sql_2);
$stmt->execute($params_2);
for(; $row=$stmt->fetch(PDO::FETCH_ASSOC);) {
$jsonEncode->encode($row);
}
// Free statement resources and close the cursor.
$stmt->closeCursor();
// End JSON array inside object
$jsonEncode->endArray();
// End JSON object
$jsonEncode->endObject();
$jsonEncode = null;
$jsonEncode = null; 将生成的JSON进行流式传输。