当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Combine Two Arrays into One array1=11,12,1 array2=am,pm,am to 11am, 12pm, 1am?

问题描述:

[time] => Array

(

[0] => 4

[1] => 5

)

[ampm] => Array

(

[0] => AM

[1] => PM

)

I need this to output as 4am,5pm ... is this possible?

网友答案:

This should work for you:

(Time and ampm have to have the same amount of values)

<?php

    $array = array(
                "time" => array(4, 5),
                "ampm" => array("AM", "PM")
            );

    $output = array();

    for($count = 0; $count < count($array["time"]); $count++)
        $output[] = $array["time"][$count] . " " . $array["ampm"][$count];

    print_r($output);

?>

Output:

Array ( [0] => 4 AM [1] => 5 PM )

EDIT:

If you want to display each array values in one row use this:

//print_r($output); delete this and write:

foreach($output as $value)
    echo $value . "<br />";

Output:

4 AM
5 PM
网友答案:

You can use array_map to combine the elements of multiple arrays:

$newArray = array_map(function($a, $b) {
    return $a . strtolower($b);
}, $oldArray['time'], $oldArray['ampm']);
网友答案:
<?php

$myArray = [
    'time' => ['4', '5', '11'],
    'ampm' => ['AM', 'PM', 'PM']
];

foreach ($myArray['time'] as $key => $time) {
    echo $time . $myArray['ampm'][$key];
}

this only works while $myArray['time'] and $myArray['ampm'] have a equal number of elements.

i'm not sure if i understood your question correctly. hope this helps.

网友答案:

You didn't supply the "why" here yesterday but commented in the meantime that the purpose is to schedule interviews on a given date. Whether limited by business hours or simply common sense, or indeed over a 24 hour span, you could create meaningful objects that can be displayed in any possible way rather than merging funny arrays. Here is a simple example that includes your time zone, can be displayed in any possible way for output etc, it may get you started at least - please check the documentation, it is all there:

$start = new DateTime('2014-12-20 00:00:00');
$interval = 'PT1H'; ' 1 hour intervals

foreach (new DatePeriod($start, new DateInterval($interval), 23) as $period) :
    var_dump($period);
endforeach;
分享给朋友:
您可能感兴趣的文章:
随机阅读: