数组未添加到foreach循环中的变量

时间:2018-08-30 18:47:56

标签: php laravel-5 foreach

遇到一个奇怪的问题,我正在用它拔头发。

我有这个foreach循环

$rubrics = ReaderRubric::where('cycle_subpool_id', "=", $cycle_subpool_id)->get();
foreach ($rubrics as &$rubric) {
    $answers = ReaderRubricAnswer::where('rubric_id', "=", $rubric->rubric_id)->get();
    $rubric['answers'] = $answers;
}

unset($rubric);

Log::info($rubrics);
return $rubrics;

$rubrics的日志

[{"rubric_id":1,"reader_type":24,"document_type":"0","title":"test","question":"qweqwe","activity_type":null},{"rubric_id":2,"reader_type":21,"document_type":"0","title":"test","question":"testing","activity_type":null}]

$rubric['answer']循环中的日志

[{"answer_id":5,"rubric_id":2,"text":"asn 1","value":1},{"answer_id":6,"rubric_id":2,"text":"ans 2","value":2},{"answer_id":7,"rubric_id":2,"text":"ans 3","value":3}]

var_dump($ rubrics);

object(Illuminate\Database\Eloquent\Collection)#74 (1) {
  ["items":protected]=>
  array(2) {
    [0]=>
    object(Entrada\Modules\Admissions\Models\Entrada\ReaderRubric)#75 (26) {
      ["dateFormat":protected]=>
      string(1) "U"
      ["connection":protected]=>
      string(16) "entrada_database"
      ["table":protected]=>
      string(24) "admissions_reader_rubric"
      ["primaryKey":protected]=>
      string(9) "rubric_id"
      ["fillable":protected]=>
      array(5) {
        [0]=>
        string(11) "reader_type"
        [1]=>
        string(13) "document_type"
        [2]=>
        string(5) "title"
        [3]=>
        string(8) "question"
        [4]=>
        string(13) "activity_type"
      }

如果我检查$rubrics$rubric['answers']的日志,则完全正确。

但是,如果我转储$rubrics,它们中的任何一个都没有$rubric['answers']

我知道这很简单,我盯着它看太久了,现在看不到它。

谢谢!

2 个答案:

答案 0 :(得分:2)

使用普通的PHP数组时,有几种方法可以解决此问题。但是由于您有一个Collection,所以某些类似行为的数组不起作用。我认为这个小变通办法应该足以使“神奇”的吸气剂/吸气剂发挥作用:

foreach ($rubrics as $key => $rubric) {
  $answers = ReaderRubricAnswer::where('rubric_id', "=", $rubric->rubric_id)->get();
  $rubric['answers'] = $answers;
  $rubrics[$key] = $rubric;
  Log::info($rubrics[$key]['answers']);
 }

答案 1 :(得分:0)

$rubrics不是数组,它是实现Traversable数组的对象,因此您可以对其进行迭代。

您可以让循环将元素推入真实数组中。

$rubrics_array = [];
foreach ($rubrics as $rubric) {
    // do stuff to $rubric
    // ...
    $rubrics_array[] = $rubric;
}

从这里开始,使用$rubrics_array代替$rubrics