John Davidson

Merge array with same value in same key php

0 comments
Message:


I have this code:


$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++;
}

When I print it it shows me this


    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
)

)

)

I want to combine an array that have the same dates to display like this:


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
)

)

)

I want to merge the array those with the same dates. I don't know how to explain it exactly, above I showed what I would like to achieve. I have already written thousands of lines of code using foreach and have not been able to achieve this :(



My Answer:
>get_items() as $item) {_$product_id = $item->get_product_id();_$product_name = $item->get_name();_$product_quantity = $item->get_quantity();_$product_price = $item->get_total();_$product_array[] = array( 'product_id' => $product_id, 'product_name' => $product_name, 'product_quantity' => $product_quantity, 'product_price' => $product_price );_}_foreach ($product_array as $product) {_$product_id = $product['product_id'];_$product_name = $product['product_name'];_$product_quantity = $product['product_quantity'];_$product_price = $product['product_price'];_if (array_key_exists($product_id, $daty)) {_$daty[$product_id]['product_quantity'] += $product_quantity;_$daty[$product_id]['product_price'] += $product_price;_} else {_$daty[$product_id] = array( 'product_id' => $product_id, 'product_name' => $product_name, 'product_quantity' => $product_quantity, 'product_price' => $product_price );_}_}$merged_array = array_values($daty);_print_r($merged_array);

Rate this post

4 of 5 based on 5373 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us