![php json时间数组格式转换:如何将歌词时间戳转换为[分:秒.毫秒]格式?](https://img.php.cn/upload/article/001/246/273/174045230714802.jpg)
PHP JSON数据处理:歌词时间戳格式转换
本文介绍如何使用PHP处理JSON数据,将歌词时间戳转换为[分:秒.毫秒]格式。
问题描述
已知一个JSON数据,包含歌词行和对应的时间戳:
立即学习“PHP免费学习笔记(深入)”;
<code class="json">{
"lrc": [
{
"linelyric": "give it away (放弃) - penthox/paul rey",
"time": "0.92"
},
{
"linelyric": "//",
"time": "1.58"
}
]
}</code>目标是将其转换为以下格式:
<code>[00:00.92]give it away (放弃) - penthox/paul rey [00:01.58]//</code>
解决方案
首先,使用json_decode()函数解析JSON字符串:
<code class="php">$jsonData = json_decode($jsonString, true); // true for associative array</code>
然后,遍历歌词数组,对每个时间戳进行格式化:
<code class="php">$formattedLrc = [];
foreach ($jsonData['lrc'] as $lrcRow) {
$time = (float)$lrcRow['time'];
$minutes = floor($time / 60);
$seconds = floor($time % 60);
$milliseconds = round(($time - floor($time)) * 100); //保留两位小数
$formattedTime = sprintf("[%02d:%02d.%02d]", $minutes, $seconds, $milliseconds);
$formattedLrc[] = $formattedTime . $lrcRow['linelyric'];
}</code>最后,将格式化后的歌词数组输出:
<code class="php">echo implode("\n", $formattedLrc);</code>此代码直接使用时间戳的小数部分作为毫秒,无需额外的计算。 如果time字段的精度更高,需要调整$milliseconds的计算方式。 最终输出结果将是符合要求的格式化歌词文本。
以上就是PHP JSON时间数组格式转换:如何将歌词时间戳转换为[分:秒.毫秒]格式?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号