我有以下几点
->select(DB::raw('source as Source, customer as Customers, COUNT(*) as count'))
->groupBy('source', 'customer')
->get();我得到了下面的结果
Illuminate\Support\Collection {#460 ▼
#items: array:4 [▼
0 => {#466 ▼
+"Source": "Facebook"
+"Customer": "Yes"
+"count": 227
}
1 => {#463 ▼
+"Source": "PinInterest"
+"Customer": "Yes"
+"count": 370
}
2 => {#465 ▼
+"Source": "PinInterest"
+"Customer": "No"
+"count": 133
}
3 => {#467 ▼
+"Source": "Whatsapp"
+"Customer": "No"
+"count": 254
}
]
}现在,根据客户的不同,来源可以是1- 10个不同的渠道。现在客户为是或否。
如何添加modify集合来添加源Facebook,Customer No和Count 0,源WhatsApp,Customer Yes和Count 0
来源: Facebook客户:是计数: 227
来源: Facebook Customer : No Count :0
来源: Whatsapp客户:无计数: 254
来源: Whatsapp客户:是计数:0
发布于 2021-02-06 21:44:44
使用laravel的集合助手,您可以在原始集合中添加缺少的数据,如下所示
转型
/** Result from original query */
$collection = collect([
["Source"=>"Facebook","Customer"=> "Yes","count"=> 227],
["Source"=>"PinInterest","Customer"=> "Yes","count"=> 370],
["Source"=>"PinInterest","Customer"=>"No","count"=> 133],
["Source"=>"Whatsapp","Customer"=> "No","count"=>254]
]);
/** Unique list of sources */
$sources = $collection->pluck('Source')->unique();
/** Unique list of customers */
$customers = collect(["Yes","No","May Be"]);
$sources->each(function ($source, $sourceKey) use (&$collection,$customers) {
if($collection->where('Source', $source)->count() < count($customers)){
$customers->each(function ($customer, $customerKey) use (&$collection,$source) {
if($collection->where('Source', $source)->where('Customer', $customer)->count() === 0){
$collection = $collection->merge([["Source"=>$source,"Customer"=> $customer,"count"=>0]]);
}
});
}
});
/** Sort and print */
echo "<pre>";
print_r($collection->sortBy('Source')->toArray());
echo "</pre>";输出
Array
(
[0] => Array
(
[Source] => Facebook
[Customer] => Yes
[count] => 227
)
[4] => Array
(
[Source] => Facebook
[Customer] => No
[count] => 0
)
[5] => Array
(
[Source] => Facebook
[Customer] => May Be
[count] => 0
)
[1] => Array
(
[Source] => PinInterest
[Customer] => Yes
[count] => 370
)
[2] => Array
(
[Source] => PinInterest
[Customer] => No
[count] => 133
)
[6] => Array
(
[Source] => PinInterest
[Customer] => May Be
[count] => 0
)
[3] => Array
(
[Source] => Whatsapp
[Customer] => No
[count] => 254
)
[7] => Array
(
[Source] => Whatsapp
[Customer] => Yes
[count] => 0
)
[8] => Array
(
[Source] => Whatsapp
[Customer] => May Be
[count] => 0
)
)https://stackoverflow.com/questions/66050224
复制相似问题