简体   繁体   中英

PHP Copy two (2) Values (Not Keys) from one array into new array

I thought this would be simple but after reviewing a couple dozen SO posts, I am not finding an answer to how to extract two of the values (not keys) from each of the arrays and create a new array out of those values. What I have is:

Array
(
    [0] => Array
        (
            [Start_DateTime] => 2022-09-07T10:00:00-07:00
            [id] => 2483148000035208002
            [End_DateTime] => 2022-09-07T10:30:00-07:00
        )

    [1] => Array
        (
            [Start_DateTime] => 2022-09-07T12:30:00-07:00
            [id] => 2483148000035208018
            [End_DateTime] => 2022-09-07T13:30:00-07:00
        )

    [2] => Array
        (
            [Start_DateTime] => 2022-09-07T15:30:00-07:00
            [id] => 2483148000035208034
            [End_DateTime] => 2022-09-07T16:15:00-07:00
        )

)

What I want is:

$appointments = [
['2022-09-07T10:00:00-07:00', '2022-09-07T10:30:00-07:00'], // Note: format is [Start, End]
['2022-09-07T12:30:00-07:00', '2022-09-07T13:30:00-07:00'],
['2022-09-07T15:30:00-07:00', '2022-09-07T16:15:00-07:00']
];

Use array_map() with a callback function that returns the start and end times in an array.

$appointments = array_map(function($item) {
    return [$item['Start_DateTime'], $item['End_DateTime']];
}, $array);

Just iterate over and attach a new array to the appointments for each start/end date.

$appointments = [];
foreach($array as $dataset) {
    $appointments[] = [$dataset['Start_DateTime'], $dataset['End_DateTime']];
}

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