Athari / YaLinqo

Yet Another LINQ to Objects for PHP [Simplified BSD]
https://athari.github.io/YaLinqo
BSD 2-Clause "Simplified" License
441 stars 39 forks source link

Undefined foreach variable #32

Closed RODOBTA closed 6 years ago

RODOBTA commented 6 years ago

I have the following code:

$modulos = from($result)->where(function($item){ return $item->Padre == 0; })->toList();
foreach($modulos as $m){
     $childs = from($result)->where(function($item){ return $item->Padre == $m->Id; })->toList();
     $m->Children = $childs;
}
return $modulos;

However variable $m undefined, something am I doing wrong? or am I missing something?

Athari commented 6 years ago

@RODOBTA Importing of variables into scope of closures is explicit in PHP, you need to specify used variable names for anonymous functions:

from($result)
  ->where(
    function($item) use($m) {
      return $item->Padre == $m->Id;
    }
  )
  ->toList();

Note that your code can be rewritten as a single query:

from($result)
  ->where(function($item) { return $item->Padre == 0; })
  ->select(function($item) {
    $item->Children = from($result)
      ->where(function($subitem) use($item) { return $subitem->Padre == $item->Id; })
      ->toList();
    return $item;
  })
  ->toList();

(Code not tested.)

RODOBTA commented 6 years ago

@Athari Thanks for the solution, it worked perfectly.