开发者

How to combine two arrays of same length to one array with two fields (not append/merge)

开发者 https://www.devze.com 2022-12-31 17:32 出处:网络
Say, I 开发者_JS百科have an array with months $months = array(\'Jan\', \'Feb\', \'Mar\'...\'Dec\');

Say, I 开发者_JS百科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


Given that the order of both arrays is the same:

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


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.


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.


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...


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消