Search code examples
phparraysarray-combine

Array Combine in PHP


I am trying to combine keys and values in arrays. I have an product_id with different price. Let say

Product id and price 

id 101 and price is 100

id 105 and price is 200

id 101 and price is 300

list of product ids in array with $product_ids[] and list of price also $price_amount[] So I preferred to combine the two arrays using array_combine

I made array_combine($product_ids,$price_amount); Now it appears look like this way

array(2) { [101]=> float(100) [105]=> float(300) } 

Is there is a way to add the key elements to the id as something like

array(2) {
    [101] => float(400) (100+300)
    [105] => float(300)
}

Here is the idea i tried

 $products = array();
 $order_totalss = array();

      foreach (get_posts('post_type=shop_order&numberposts=-1&post_status=publish') as $order) {
                $order = new WC_Order($order->ID);
               if (wc_customer_bought_product($order->billing_email, $order->user_id, $product_id)) {
                    $productcounts[] = $product_id;
                    $order_totalss[] = $order->get_total();
                }

    }
    $arraymergeme = array_combine($productcounts, $order_totalss);

Solution

  • Simple code so you can see what's happening clearly:

    $ids    = array(101, 105, 101);
    $prices = array(100, 200, 300);
    
    $totals = array();
    foreach ($ids as $key => $id)
    {
        // Make sure index is defined
        if ( ! isset($totals[$id]))
        {
            // Make sure we have a value
            $totals[$id] = 0;
        }
    
        // Assuming index $key matches... add to the total
        $totals[$id] += $prices[$key];
    }