douhan4093 2017-05-19 21:09
浏览 879

如何使用laravel集合从多维数组中获取匹配值的数组

I have response like:

Array (
    [0] => Array (
            [0] => Array (
                    [Product] => 'Product1'
                    [Total] => $10
                   )
            [1] =>  Array (
                     [Product] => 'Product2'
                     [Total] => $50 
                   )
           )    
    [1] => Array (
           [0] => Array (
                   [Product] => 'Product1'
                   [Total] => $20
                  )
           [1] => Array (
                   [Product] => 'Product2'
                   [Total] => $30 
                  )
           )
    [2] => Array (
           [0] => Array (
                   [Product] => 'Product1'
                   [Total] => $0
                  )
           [1] => Array (
                   [Product] => 'Product2'
                   [Total] => $10 
           )
      )
 )

I want to get array of Total of Product1 but only using laravel collection.

I have tried :

$data = [];
    $collection = collect($monthly_usage_data)->each(function ($item, $key) {
            $data['Total'][$key] = str_replace('$', '', collect($item)->where('Product', 'Product1')->pluck('Total'));
            echo str_replace('$', '', collect($item)->where('Product', 'Product1')->pluck('Total'));
    });

When i print $data it shows blank array; When i echo inside each it ll give ["10"]["20"]["0"] .

Can somebody tell me right way to use collection to get array of total of product1

  • 写回答

2条回答 默认 最新

  • du3669 2017-05-19 21:16
    关注

    Remember that functions have their own scopes. $data in the global scope is not the same as $data inside your function unless you import it.

    You can import variables into anonymous functions with use:

    function ($item, $key) use ($data) {
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度