简体   繁体   中英

Merge two associative PHP arrays with different keys

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) :(

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM