在相同的关键字php中合并具有相同值的数组



我有这个代码:

$order = wc_get_order( 988613 );
$product_array = array();
$daty = array();
$counter = 1;
foreach ($order->get_items() as $item_key => $item ){

$daty_dostaw = $item->get_meta('Daty dostaw');
$product_id = $item->get_product_id();

$daty_dostaw_explode = explode(',',$daty_dostaw);


$daty[$counter]['product_id'] = $product_id;


foreach($daty_dostaw_explode as $key => $data){
$daty[$counter]['data'][] = $data;
}
$counter++; 
}

当我打印它时,它会显示这个

Array
(
[1] => Array
(
[product_id] => 988012
[data] => Array
(
[0] => 13-08-2022
[1] => 25-08-2022
[2] => 30-08-2022
)
)
[2] => Array
(
[product_id] => 988087
[data] => Array
(
[0] => 25-08-2022
[1] => 31-08-2022
[2] => 30-09-2022
)
)
)

我想组合一个具有相同日期的数组,显示如下:

Array
(   [1] => Array
(
[product_id] => array(988012, 988087)
[data] => Array
(
[0] => 25-08-2022
)
)
[2] => Array
(
[product_id] => 988012
[data] => Array
(
[0] => 13-08-2022
[1] => 30-08-2022
)
)
[3] => Array
(
[product_id] => 988087
[data] => Array
(
[0] => 31-08-2022
[1] => 30-09-2022
)
)
)

我想把那些日期相同的数组合并起来。我不知道如何准确地解释,上面我展示了我想要实现的目标。我已经使用foreach编写了数千行代码,但未能实现这一点:(

如果存在多个日期相同的产品,基本上您希望将product_id转换为一个数组。我会搜索这样的匹配,创建合并,从单个引用中删除元素,甚至在单个引用被清空时删除元素。一个例子是:

$cachedDates = []; //Here we will store the dates we have gone through so far
foreach ($product_array as $key => $product) {
foreach ($product_array[$key]["data"] => $date) {
if (!in_array($date, $cachedDates)) {
//Creating a cache entry for this date
$cachedDates[$date] = ["keys" => [], "values" => []];
}
//Adding the key and product to the date's cache
$cachedDates[$date]["keys"][]= $key;
$cachedDates[$date]["values"][]= $product["product_id"];
}
}
//Adding the new items to $product_array and cleaning up items that become redundant
foreach ($cachedDates as $date => $entry) {
//We only merge items that have a not-unique date
if (count($entry["values"]) > 0) {
//adding a new item with the correct values and the date
$product_array[]= [
"product_id" => $entry["values"],
"data" => $date
];
//Cleanup
for ($index = 0; $index < count($entry["keys"]); $index++) {
//We remove the date from the data entry after finding its index
$removeIndex = array_search($date, $product_array[$entry["keys"][$index]]["data"]);
unset($product_array[$entry["keys"][$index]]["data"][$removeIndex]);
//If the data array is empty, then the whole product was already merged into some other item(s)
if (!count($product_array[$entry["keys"][$index]]["data"])) {
unset($product_array[$entry["keys"][$index]]);
}
}
}
}

上面的代码未经测试,如果您发现它有问题和错误,请提供适当的PHP输入而不是打印,即使json_encode结果也足够好

最新更新