0

Imagine two associative arrays:

$array1= array(
        array('date'=>'1-Sep-2016', 'price1'=>98),
        array('date'=>'1-Oct-2016', 'price1'=>77),
        array('date'=>'1-Nov-2016', 'price1'=>87),
        array('date'=>'1-Dec-2016', 'price1'=>88),
        array('date'=>'1-Jan-2017', 'price1'=>91)
        );

$array2= array(
        array('date'=>'1-Feb-2016', 'price2'=>98),
        array('date'=>'1-Mar-2016', 'price2'=>77),
        array('date'=>'1-Apr-2016', 'price2'=>87),
        array('date'=>'1-May-2016', 'price2'=>88),
        array('date'=>'1-Jun-2016', 'price2'=>91),
        array('date'=>'1-Jul-2016', 'price2'=>88),
        array('date'=>'1-Aug-2016', 'price2'=>88),
        array('date'=>'1-Sep-2016', 'price2'=>88),
        array('date'=>'1-Oct-2016', 'price2'=>88)
        );

The merged array should look like:

$merged =array(
        array('date'=>'1-Feb-2016', 'price2'=>98),
        array('date'=>'1-Mar-2016', 'price2'=>77),
        array('date'=>'1-Apr-2016', 'price2'=>87),
        array('date'=>'1-May-2016', 'price2'=>88),
        array('date'=>'1-Jun-2016', 'price2'=>91),
        array('date'=>'1-Jul-2016', 'price2'=>88),
        array('date'=>'1-Aug-2016', 'price2'=>88),
        array('date'=>'1-Sep-2016', 'price1'=>98, 'price2'=>88),
        array('date'=>'1-Oct-2016', 'price1'=>77, price2'=>88),
        array('date'=>'1-Nov-2016', 'price1'=>87),
        array('date'=>'1-Dec-2016', 'price1'=>88),
        array('date'=>'1-Jan-2017', 'price1'=>91)
};

Note below lines:

  array('date'=>'1-Sep-2016', 'price1'=>98, 'price2'=>88),
  array('date'=>'1-Oct-2016', 'price1'=>77, price2'=>88),

In short: I need to merge combine two arrays without removing any element from either array. Array1 will always contain date and price1 elements while array2 will always contain date and price2 elements. So if both array contain the same date (example: 1-Sep-2016) the result array (merged) need to have them them merged by adding price1 and price2 elements as well. I hope you got my point (sorry, not a native English speaker) :(

virrion
  • 416
  • 1
  • 5
  • 18
  • Possible duplicate of [php array\_merge associative arrays](http://stackoverflow.com/questions/5233721/php-array-merge-associative-arrays) – Script47 Jan 11 '16 at 23:39
  • @Script47 Appreciate your suggestion. However, I've not been able to use the post you suggested. Neither answer helped me to get array combined the way I explained. – virrion Jan 12 '16 at 00:00

1 Answers1

4

You can do this by using the date as a key in your merged array.

$i = 1;
foreach (array($array1, $array2) as $array) { 
    foreach ($array as $entry) {
        $key = strtotime($entry['date']); // convert to a timestamp so it will be sortable
        $new_array[$key]['date'] = $entry['date'];
        $new_array[$key]["price$i"] = $entry["price$i"];
    }
    $i++;
}

Then if you want the results to be sorted, you can use

ksort($new_array);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80