PHP JSON时间数组格式转换:如何将歌词时间戳转换为[分:秒.毫秒]格式?

php json时间数组格式转换:如何将歌词时间戳转换为[分:秒.毫秒]格式?

PHP JSON数据处理:歌词时间戳格式转换

本文介绍如何使用PHP处理JSON数据,将歌词时间戳转换为[分:秒.毫秒]格式。

问题描述

已知一个JSON数据,包含歌词行和对应的时间戳:

立即学习PHP免费学习笔记(深入)”;

{
  "lrc": [
    {
      "linelyric": "give it away (放弃) - penthox/paul rey",
      "time": "0.92"
    },
    {
      "linelyric": "//",
      "time": "1.58"
    }
  ]
}
登录后复制

目标是将其转换为以下格式:

[00:00.92]give it away (放弃) - penthox/paul rey
[00:01.58]//
登录后复制

解决方案

首先,使用json_decode()函数解析JSON字符串:

$jsonData = json_decode($jsonString, true); // true for associative array
登录后复制

然后,遍历歌词数组,对每个时间戳进行格式化:

$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'];
}
登录后复制

最后,将格式化后的歌词数组输出:

echo implode("
", $formattedLrc);
登录后复制

此代码直接使用时间戳的小数部分作为毫秒,无需额外的计算。 如果time字段的精度更高,需要调整$milliseconds的计算方式。 最终输出结果将是符合要求的格式化歌词文本。

以上就是PHP JSON时间数组格式转换:如何将歌词时间戳转换为[分:秒.毫秒]格式?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1233235.html

发表回复

Your email address will not be published. Required fields are marked *