Laravel 8 Blade遍历Google语音转文字接口返回嵌套数组的实现方案
问题原因
报错Cannot access offset of type string on string的本质是你尝试用数组键访问字符串类型的值,常见触发场景有两种:
- 控制器传递到视图的
wordMetaData没有正确转为数组,依然是Google接口返回的JSON字符串 - Blade遍历的时候层级写错,直接遍历了上层的字符串字段(比如
transcript)而不是嵌套的单词数组
正确实现步骤
1. 控制器侧代码(确保传递结构正确)
拿到Google Speech to Text的返回后,要确认wordMetaData是数组格式再传到视图,示例代码:
// 假设$googleResponse是Google API返回的结果 $transcriptResult = [ 'transcript' => $googleResponse->getAlternatives()[0]->getTranscript(), 'confidence' => $googleResponse->getAlternatives()[0]->getConfidence(), 'wordMetaData' => collect($googleResponse->getAlternatives()[0]->getWords())->map(function ($wordInfo) { return [ 'word' => $wordInfo->getWord(), 'startTime' => $wordInfo->getStartTime()->getSeconds() + $wordInfo->getStartTime()->getNanos() / 1e9, 'endTime' => $wordInfo->getEndTime()->getSeconds() + $wordInfo->getEndTime()->getNanos() / 1e9, ]; })->toArray() // 必须转为数组,禁止直接传递对象或者JSON字符串 ]; // 传递到视图 return view('你的blade模板名', compact('transcriptResult'));
2. Blade视图侧渲染代码
{{-- 基础信息展示 --}} <p>转写全文:*{{ $transcriptResult['transcript'] }}*</p> <p>识别置信度:*{{ number_format($transcriptResult['confidence'] * 100, 2) }}%*</p> {{-- 单词时间表格 --}} <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>序号</th> <th>单词内容</th> <th>开始时间(秒)</th> <th>结束时间(秒)</th> </tr> </thead> <tbody> @foreach($transcriptResult['wordMetaData'] as $index => $wordItem) <tr> <td>{{ $index + 1 }}</td> <td>{{ $wordItem['word'] }}</td> <td>{{ number_format($wordItem['startTime'], 3) }}</td> <td>{{ number_format($wordItem['endTime'], 3) }}</td> </tr> @endforeach </tbody> </table>
排障校验方法
如果仍然报错,可以先在Blade顶部加调试代码,确认传参结构正确:
{{ dd($transcriptResult) }}
正常输出的结构应该为:
array:3 [
"transcript" => "你好世界这是测试转写"
"confidence" => 0.9423
"wordMetaData" => array:4 [
0 => array:3 ["word" => "你好", "startTime" => 0.1, "endTime" => 0.3]
1 => array:3 ["word" => "世界", "startTime" => 0.32, "endTime" => 0.58]
...
]
]
如果wordMetaData字段显示为字符串,说明控制器侧没有正确解析接口返回的嵌套数据,需要先把对应的JSON转为数组再传参。
内容的提问来源于stack exchange,提问作者LaFllamme
相关产品推荐
相关产品推荐

