我有一个包含特定brand_id的数组,在这些品牌中,我有一个销售日期数组但这些是基于销售产品的,所以它们可能会在同一个brand_id上出现多次;
这是我的数组
array:5 [▼
2 => array:3 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
]
3 => array:5 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
3 => "2022-05-08"
4 => "2022-05-08"
]
4 => array:1 [▼
0 => "2022-05-08"
]
1 => array:3 [▼
0 => "2022-05-01"
1 => "2022-05-08"
2 => "2022-05-08"
]
6 => array:3 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
]
]
生成它的代码:
pastSales = [];
$historySales = SaleHistoryCount::all()->toArray();
foreach($historySales as $key => $historySale) {
$saleDateToCompare = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['sale_date'])
->format('Y-m-d');
if(in_array($saleDateToCompare , $saleDays)) {
if(! isset($pastSales[$historySale['sale_date']])) {
$pastSales [$historySale['brand_id']][] = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['brand_id'])
->format('Y-m-d');
}
}
}
$saleDays
是每个星期日的二维数组,直到某一年,如
[
"2022-05-08"
"2022-05-15"
"2022-05-22"
]
所有的重复项剥离,并有它减少到一个,除非日期是不同的每个brand_id,但我似乎无法产生与array_unique, array_mapping和/或array_columns…我如何实现下面的输出?
array:5 [▼
2 => array:3 [▼
0 => "2022-05-08"
]
3 => array:5 [▼
0 => "2022-05-08"
]
4 => array:1 [▼
0 => "2022-05-08"
]
1 => array:3 [▼
0 => "2022-05-01"
2 => "2022-05-08"
]
6 => array:3 [▼
0 => "2022-05-08"
]
]
按照Tim Lewis的建议使用in_array
:
foreach($historySales as $key => $historySale) {
$saleDateToCompare = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['sale_date'])
->format('Y-m-d');
if(in_array($saleDateToCompare , $saleDays)) {
$date_formatted = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['brand_id'])->format('Y-m-d');
// !!! Is this string correct? Maybe we should check for "$historySale['brand_id']" existance?
if(! isset($pastSales[$historySale['sale_date']]))
$pastSales[$historySale['brand_id']] = [];
if( !in_array($date_formatted, $pastSales[$historySale['brand_id']]) )
$pastSales[$historySale['brand_id']][] = $date_formatted;
}
}