JonYork
JonYork

Reputation: 1243

Array not being added to variable in foreach loop

Ran into a weird problem and I'm pulling my hair out with it.

I've got this foreach loop

$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;

Log of $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}]

Log of $rubric['answer'] in loop

[{"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"
      }

If I check the logs for $rubrics and $rubric['answers'] it's exactly as it should be.

However, if I var dump $rubrics, none of them have the $rubric['answers'] to them.

I know it's something simple, I've just been staring at it too long to see it now.

Thanks!

Upvotes: 0

Views: 49

Answers (2)

jh1711
jh1711

Reputation: 2328

When you work with normal PHP arrays, there are a few ways to handle this. But since you have a Collection some array like behavior does not work. I think this little workaround should be enough to make the 'magic' getters/setters work:

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']);
 }

Upvotes: 2

Barmar
Barmar

Reputation: 780909

$rubrics is not an array, it's an object that implements the Traversable array, so you can iterate over it.

You can have your loop push the elements onto a real array.

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

From here on, use $rubrics_array instead of $rubrics.

Upvotes: 0

Related Questions