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

Php 如何使用laravel集合从多维数组中获取匹配值的数组,php,multidimensional-array,laravel-5,laravel-collection,Php,Multidimensional Array,Laravel 5,Laravel Collection,我的回答是: Array ( [0] => Array ( [0] => Array ( [Product] => 'Product1' [Total] => $10 ) [1] => Array ( [Product] => 'Product2

我的回答是:

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 
           )
      )
 )
我想获得Product1的总计数组,但仅使用

我试过:

$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'));
    });
当我打印$数据时,它显示空白数组;当我在每个内部回音时,它将给出[10][20][0]


有人能告诉我使用collection获取product1总计数组的正确方法吗?记住函数有自己的作用域$全局范围中的数据与函数中的$data不同,除非您导入它

您可以使用以下命令将变量导入匿名函数:

function ($item, $key) use ($data) {

}

通常,您可以使用以下方法:

$totals = $collection->where('Product', 'Product1')->mapWithKeys(function ($item) {
    return $item['Total'];
});

$totals->all();

收集$item->where'Product','Product'对我来说是个问题。我认为您可能过于依赖集合,而不是仅使用数组映射函数。很抱歉,我的错误是product1 collect$item->where'Product',product1'仍然获得空白数组,这意味着您的函数未执行。我有echo该值正在打印[10][20][0]向代码添加更新不要覆盖现有代码,请将其添加到下面it@Omi我看到您进行了编辑,但仍然没有看到您导入$数据