You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中从JSON数组提取RoundNumber属性报错解决

解决方法

首先明确核心问题:MatchingTables是数组类型,不能直接通过对象属性访问的方式获取RoundNumber,必须遍历数组中的每个元素。

1. 先确认JSON结构(可选但推荐)

可以先打印解码后的结构,确保你对数据层级的判断正确:

dd($decoded->data->MatchingTables);

2. 提取所有RoundNumber的两种有效写法

方式一:foreach循环遍历

直接遍历数组,逐个提取每个元素的RoundNumber:

public function importResults(Request $request)
{
    $json = file_get_contents($request->file('results'));
    $decoded = json_decode($json);

    $roundNumbers = [];
    // 遍历MatchingTables数组中的每一项
    foreach ($decoded->data->MatchingTables as $tableItem) {
        $roundNumbers[] = $tableItem->RoundNumber;
    }

    return $roundNumbers;
    // return redirect('getPanel');
}

方式二:Laravel集合简化操作

利用Laravel的集合类,用更简洁的代码完成提取:

public function importResults(Request $request)
{
    $json = file_get_contents($request->file('results'));
    $decoded = json_decode($json);

    // 转集合后直接pluck提取指定属性,再转数组返回
    $roundNumbers = collect($decoded->data->MatchingTables)->pluck('RoundNumber')->toArray();

    return $roundNumbers;
    // return redirect('getPanel');
}

3. 之前写法错误的原因

  • $decoded->data->MatchingTables->RoundNumber:将数组当作对象访问属性,触发“Attempt to assign property 'RoundNumber' on array”错误。
  • $decoded->data->MatchingTables["RoundNumber"]:数组的索引是数字(列表型数组),而非字符串"RoundNumber",所以无法取到值。
  • $decoded->data->MatchingTables[]->RoundNumber:属于PHP语法错误,不支持这种遍历写法。

内容的提问来源于stack exchange,提问作者Leonardo Gori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:07