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

Time:08-30

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']
];

CodePudding user response:

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

CodePudding user response:

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']];
}
  • Related