在PHP中过滤数组

时间:2013-02-14 21:18:38

标签: php

我正在尝试使用lambda语法在PHP中使用数组过滤器函数编写排序/过滤器脚本。

这实现了我想要做的事情,但看起来它可以被优化:

$offersReceivedProcessedByItem = array();
  foreach ($this->currentSessionUser->items as $item) {
    $receivedOffersOnItem = array();
    foreach ($offersReceived as $offerReceived) {
     if ($offerReceived->item->id === $item->id) {
       $receivedOffersOnItem[$offerReceived->id] = $offerReceived;
     }
    }
  offersReceivedProcessedByItem[$item->id] = $receivedOffersOnItem;
}

(对于用户拥有的每个项目,过滤offerReceived数组并将商品添加到新数组中,如果它具有相同的ID,如果有意义的话?)。

以下是我正在尝试的内容:

$offersReceivedProcessedByItem = array();
foreach ($this->currentSessionUser->items as $item) {
   $receivedOffersOnItem = array_filter($item->offers, function($offer){
     return $offer->item->id === $item->id;
   });
   $offersReceivedProcessedByItem[$item->id] = $receivedOffersOnItem;
}

但是我得到$ item是未定义的,我希望它是封闭的范围,所以我尝试将$ item作为另一个参数传递,但后来我得到'缺少参数2'。

我尝试使用Fuel内置的关系方法,但PHP占用了太多内存而失败了。

有任何帮助吗?我错了什么?

1 个答案:

答案 0 :(得分:2)

除非你告诉它,否则一个闭包对它所创建的环境一无所知

$receivedOffersOnItem = array_filter($item->offers, function($offer) use($item){
   return $offer->item->id === $item->id;
});

注意use - 声明

手册http://php.net/functions.anonymous#example-119

的链接