分享一個 PHP 版的 JSON 資料格式化函數_PHP教程

來源:互聯網
上載者:User
今天在芒果小站看到一段代碼,感覺挺不錯的,於是轉載過來。以下是原文。

將字串形式的 JSON 資料格式化為縮排形式。通常使用 json_encode 轉換出來的 JSON 串沒有縮排,有這個方法就爽多了。
這裡我預設使用了 tab 縮排,如果要改成空格,替換變數 $indentStr 即可。

/**
* Indents a flat JSON string to make it more human-readable.
* @param string $json The original JSON string to process.
* @return string Indented version of the original JSON string.
*/
function indent ($json) {

$result = '';
$pos = 0;
$strLen = strlen($json);
$indentStr = ' ';
$newLine = "\n";
$prevChar = '';
$outOfQuotes = true;

for ($i=0; $i<=$strLen; $i++) {

// Grab the next character in the string.
$char = substr($json, $i, 1);
// Are we inside a quoted string?
if ($char == '"' && $prevChar != '\\') {
$outOfQuotes = !$outOfQuotes;
// If this character is the end of an element,
// output a new line and indent the next line.
} else if(($char == '}' || $char == ']') && $outOfQuotes) {
$result .= $newLine;
$pos --;
for ($j=0; $j<$pos; $j++) {
$result .= $indentStr;
}
}
// Add the character to the result string.
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line.
if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
$result .= $newLine;
if ($char == '{' || $char == '[') {
$pos ++;
}
for ($j = 0; $j < $pos; $j++) {
$result .= $indentStr;
}
}
$prevChar = $char;
}

return $result;

}

http://www.bkjia.com/PHPjc/363833.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/363833.htmlTechArticle今天在芒果小站看到一段代碼,感覺挺不錯的,於是轉載過來。以下是原文。 將字串形式的 JSON 資料格式化為縮排形式。通常使用 json...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.