duangenshi9836 2013-02-14 21:18
浏览 37
已采纳

在PHP中过滤数组

I'm trying to write a sort/filter script using an array filter function in PHP using the lambda syntax.

This achieves what I want to do, but it looks like it can be optimised:

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

(for each item a user has, filter through the offersReceived array and add the offer to a new array if it has an equal id, if that makes sense?!).

Here's what I'm trying:

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

But i'm getting that $item is undefined, I expect it's closed scope so I tried passing $item as another argument but then i'm getting 'missing argument 2'.

I tried this using the relational approach built into Fuel but PHP eats too much memory and fails.

Any help? What am I getting wrong?

  • 写回答

1条回答 默认 最新

  • doukuang8166 2013-02-14 21:27
    关注

    A closure doesn't know anything about the environment it is created it unless you tell it

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

    Notice the use-statement

    A link to the manual http://php.net/functions.anonymous#example-119

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)