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

Laravel中foreach循环访问数组元素报错:尝试读取数组属性'question'

问题描述

我创建了一个自定义数组来存储问题和答案,但尝试访问数组元素时出现错误:attempt to read property "question" on array。直接从Eloquent模型获取数据时一切正常,仅使用自定义数组会报错。

相关代码

视图代码

@foreach ($questionsArray as $i => $data)
    <div class=" p-3 m-1 text-left">
        <p class="font-weight-bold">Q.{{$i + 1}} {{$data->question}}</p>
        <!-- 错误出在这里! -->
    </div>
@endforeach

后端代码

$questionsArray = array();

foreach ($questions as $question) {
    $answers = tbl_answer::where('answer_question_table_id', $question->question_id)->get();
    $questionsArray[] = array(
        "question" => array($question),
        "answers"  => array($answers)
    );
}

从响应结构可以看到,每个question字段对应的值是一个包含问题对象的数组。

问题原因

后端代码中,你把$question和$answers用array()额外包裹了一层,导致$questionsArray里的元素是纯关联数组,而非Eloquent对象。但视图里却使用了对象的属性访问语法->question,这就触发了"在数组上读取属性"的错误。

解决方案

方案1:调整视图的访问方式

直接适配后端的数组结构,通过数组索引访问:

@foreach ($questionsArray as $i => $data)
    <div class=" p-3 m-1 text-left">
        <p class="font-weight-bold">Q.{{$i + 1}} {{$data['question'][0]->question}}</p>
    </div>
@endforeach

方案2:优化后端数组结构(更推荐)

去掉不必要的外层数组包裹,直接存储Eloquent对象/集合:

$questionsArray = array();

foreach ($questions as $question) {
    $answers = tbl_answer::where('answer_question_table_id', $question->question_id)->get();
    $questionsArray[] = array(
        "question" => $question,
        "answers"  => $answers
    );
}

修改后视图可正常使用数组或对象语法访问:

@foreach ($questionsArray as $i => $data)
    <div class=" p-3 m-1 text-left">
        <p class="font-weight-bold">Q.{{$i + 1}} {{$data['question']->question}}</p>
        <!-- 或者用对象语法:$data->question->question -->
    </div>
@endforeach

内容的提问来源于stack exchange,提问作者swapnil mane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:15:55