tags:

views:

30

answers:

2

I have 2 arrays, each with a date string and a string value representing 'amount'. The first array has a row for every day between start_date and end_date, but has nothing for 'amount'. The second array has fewer rows, but has the amount. I need to merge the 2 arrays so that I end up with a row for every day, with an amount for that day, if there is one.

Array 1: every day, no amount:

Array(  
    [20040601] => Array( [amount] => )  
    [20040602] => Array( [amount] => )  
    ...   
    [20100506] => Array( [amount] => )  
    [20100507] => Array( [amount] => )  
)  

Array 2: unique date for each row, has amount, not an entry for every day:

Array(  
    [20040618] => Array( [amount] => 19764 )  
    [20040727] => Array( [amount] => 18008 )  
    ...  
    [20040925] => Array( [amount] => 5480 )  
    [20041007] => Array( [amount] => 12522 )  
)  

Result:

Array(  
    [20040618] => Array( [amount] => 19764 )  
    [20040619] => Array( [amount] => )  
    [20040620] => Array( [amount] => 5967)  
    [20040621] => Array( [amount] => )  
    ...
    [20040625] => Array( [amount] => 5480 )  
    [20040626] => Array( [amount] => 12522 )  
    [20040627] => Array( [amount] => 4523 )  
)  

EDIT: Showing the result array a little better.

Resulting array would include a row for every day, with the corresponding amount for that day, if there is one. So basically, merge on the date key and return the date and amount. I've tried to get merge_array to work but I am losing my date in the process. There has to be a native function to do this without resorting to iterative looping through the array.

A: 
array_merge_recursive($array1, $array2);
eliego
That still destroys the date element and returns the array appended.
Scott
+1  A: 

I've tried to get merge_array to work but I am losing my date in the process.

This is being caused by the conversion of your date string to a numeric type, which causes array_merge() to behave differently. If you use a string key that PHP won't convert to a number, it should do what you want:

$arr1 = array(
    '2004-06-01' => array('amount' => null),
    '2004-06-02' => array('amount' => null),
    '2010-05-06' => array('amount' => null),
    '2010-05-07' => array('amount' => null),
);

$arr2 = array(
    '2004-06-01' => array('amount' => 50),
    '2004-06-02' => array('amount' => 100),
    '2010-05-08' => array('amount' => 200),
    '2010-05-07' => array('amount' => 250),
);

print_r(array_merge($arr1, $arr2));
NullUserException
This is what was happening. Thanks for the help!
Scott