Skip to content

Instantly share code, notes, and snippets.

@allex
Last active March 8, 2022 18:04
Show Gist options
  • Save allex/dbd77fbed7a0519f07f7 to your computer and use it in GitHub Desktop.
Save allex/dbd77fbed7a0519f07f7 to your computer and use it in GitHub Desktop.
<?php
// Simple json combine script
// author: Allex Wang ([email protected])
// GistID: dbd77fbed7a0519f07f7
// GistURL: https://gist.github.com/allex/dbd77fbed7a0519f07f7
define('DATA_DIR', dirname(__FILENAME__) . DIRECTORY_SEPARATOR . "data");
function merge_files($list) {
$out = array();
foreach ($list as $filename) {
$arr = json_decode(file_get_contents($filename), true);
foreach ($arr as $k => $v) {
$out[$k] = $v;
}
}
return json_encode($out, JSON_UNESCAPED_SLASHES);
}
function combine($list, $flat = false) {
if ($flat) {
return merge_files($list);
} else {
$out = array();
$start = strlen(DATA_DIR) + 1;
foreach ($list as $filename) {
$k = substr($filename, 0, -5);
$k = substr($k, $start);
$out[$k] = json_decode(file_get_contents($filename), true);
}
return json_encode($out, JSON_UNESCAPED_SLASHES);
}
}
$files = array();
$dh = opendir(DATA_DIR);
while (false !== ($filename = readdir($dh))) {
$file = DATA_DIR . DIRECTORY_SEPARATOR . $filename;
if (!is_dir($file)) {
$files[] = $file;
}
}
header("Content-Type: application/json; charset=utf-8");
header("Transfer-encoding: chunked");
flush();
echo combine($files);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment