views:

146

answers:

8

Say, I have an array with months

$months = array('Jan', 'Feb', 'Mar'...'Dec');

And another, with days (say, for year 2010)

$mdays = array(31, 28, 31...31);

I want to merge/combine these two arrays, into an array like this:

$monthdetails[0] = ('month' => 'Jan', 'days' => 31)

$monthdetails[1] = ('month' => 'Feb', 'days' => 28)

...

$monthdetails[11] = ('month' => 'Dec', 'days' => 31)

I can loop through both the arrays and fill the $monthdetails. I want to know whether there are any functions/easier way for achieving the same result.

Thanks! Raj

+1  A: 

array_combine

$monthdetails = array_combine($months, $mdays);


echo $monthdetails['Jan']; //31

This isn't exactly what you're looking for, but you should adapt your system to use this method.

Tim Cooper
I cannot use this, as printing the key names isn't easy. Also, I may have to have more than 2 arrays merged in my app. The foreach/for loop method looks the only option.Thanks for the tip.
Raj
+3  A: 

Given that the order of both arrays is the same:

foreach ($months as $key => $value) {
  $monthdetails[$key] = array('month' => $value, 'days' => $mdays[$key]);
}
Alec
A: 

If you can live with an array structure like this:

Array
(
    [Jan] => 31
    [Feb] => 28
    [Mar] => 31
    ...
    [Dec] => 31
)

Then array_combine() is your friend:

$monthdetails = array_combine($months, $mdays);

It probably would be the fastest way...

Felix Kling
A: 

I believe array_combine does what you want: http://www.php.net/manual/en/function.array-combine.php

It uses the first array for keys and the second for values.

King Isaac
+1  A: 

Assuming both arrays are the same size:

$count = count($months);
$monthdetails = array();
for ($i=0; $i<$count; $i++) {
    $monthdetails[] = array('month' => $months[$i], 'days' => $mdays[$i]);
}

Edit: Like the other answers, array_combine() immediately came to mind but it doesn't do exactly what the question asked.

Edit 2: I would still recommend against using such a direct approach, since it doesn't deal with the possibility of leap years. Re-inventing the date-time wheel is usually not a good idea.

Lotus Notes
The month-days case was an example to illustrate my requirement, not the actual requirement. I am not re-inventing the good date system in php :-)Thanks for the tip.
Raj
A: 

Combine two arrays with array_combine? http://www.php.net/manual/en/function.array-combine.php

Riley
A: 
function month_callback( $month, $day ){
    return array( 'month' => $month,
                  'day' => $day );
}

$months = array( 'Jan', 'Feb', 'Mar' );
$days = array( 31, 28, 31 );

$monthdetails = array_map( 'month_callback', $months, $days );

print_r( $monthdetails );
postpostmodern
A: 

Thanks for the answers!

I am using the loop method for now, and wanted to know whether there was a builtin function/single step method to do this. Looks like none exist. Might as well continue using the foreach.

Thanks again for looking into this.

Raj