PHP如何按指定typeId从JSON结构中提取对应的date值
错误原因
- 参数传递错误:你用
file_get_contents把接口/文件内容读到了$json变量里,但是调用json_decode的时候传的还是原始的$orders参数,根本没有解析你拿到的JSON内容,自然拿不到数据。 - 语法错误:PHP原生不支持
$value->dates->[typeId='11']这种直接按属性过滤数组元素的写法,dates是索引数组,你需要遍历它才能匹配符合条件的元素。 - 属性访问错误:对象的属性需要用
->连续访问,你写的.date既不是字符串拼接也不是属性访问,语法完全不成立。
修正后的代码
$json = file_get_contents($orders); $arr = json_decode($json); foreach($arr->entries as $order => $value) { // 遍历dates数组查找typeId=11的项 $targetDate = ''; foreach ($value->dates as $dateItem) { if ($dateItem->typeId == 11) { $targetDate = $dateItem->date; break; // 找到后直接跳出循环 } } echo '<th scope="row">' . $targetDate . '</th>'; }
如果使用PHP7.4及以上版本,也可以用数组过滤简化写法:
$json = file_get_contents($orders); $arr = json_decode($json, true); // 转成关联数组处理更便捷 foreach($arr['entries'] as $value) { $targetItem = current(array_filter($value['dates'], fn($item) => $item['typeId'] == 11)); echo '<th scope="row">' . $targetItem['date'] . '</th>'; }
内容的提问来源于stack exchange,提问作者Leff
相关产品推荐
相关产品推荐

