PHP过滤Vimeo Live API响应并返回目标直播对象的问题
在PHP端过滤Vimeo Live API响应的方案
核心问题解决
PHP 8.0及以上版本支持可选链运算符?->,可以完美替代JS里的可选链逻辑,避免访问null/undefined属性时的警告。结合空合并运算符??,就能安全检查嵌套属性。
高效实现代码(推荐)
假设你已经通过PHP获取到Vimeo API返回的数组(命名为$apiResponse,包含data子数组):
// 初始化目标对象 $targetStream = null; // 遍历数组,找到第一个匹配项后立即停止 foreach ($apiResponse['data'] as $item) { // 用可选链安全访问嵌套属性,避免null警告 $liveVideoStatus = $item['metadata']['connections']['live_video']?['status'] ?? null; if ($liveVideoStatus === 'streaming') { $targetStream = $item; break; } } // 返回单个匹配对象的JSON给前端 echo json_encode($targetStream);
用array_filter的写法(适合需获取所有匹配项的场景)
如果坚持使用array_filter,同样可以结合可选链处理:
$filteredStreams = array_filter($apiResponse['data'], function($item) { $status = $item['metadata']['connections']['live_video']?['status'] ?? null; return $status === 'streaming'; }); // 取第一个匹配对象(无匹配则返回null) $targetStream = reset($filteredStreams) ?: null; echo json_encode($targetStream);
低版本PHP兼容写法(PHP 7.x及以下)
如果你的PHP版本低于8.0,用嵌套isset检查避免警告:
$targetStream = null; foreach ($apiResponse['data'] as $item) { $liveVideoStatus = null; if (isset($item['metadata']['connections']['live_video']['status'])) { $liveVideoStatus = $item['metadata']['connections']['live_video']['status']; } if ($liveVideoStatus === 'streaming') { $targetStream = $item; break; } } echo json_encode($targetStream);
内容的提问来源于stack exchange,提问作者Dirty Bird Design
相关产品推荐
相关产品推荐

