将数组重新排列为其他格式

问题描述 投票:-2回答:1

我有一个数组

 array( [7:30:00] => 7:30 [8:20:00] => 8:20 [9:10:00] => 9:10 [10:00:00] => 10:00 [10:50:00] => 10:50 [11:40:00] => 11:40 [12:30:00] => 12:30 [13:20:00] => 13:20 [14:10:00] => 14:10 [15:00:00] => 15:00 [15:50:00] => 15:50 )

所以我想像这样合并当前值和下一个值来重新排列它

Array ( [7:30:00] => 7:30 - 820 [8:20:00] => 8:20 - 9:10 [9:10:00] => 9:10 - 10:00 [10:00:00] => 10:00 - 10:50 [10:50:00] => 10:50 - 11:40 [11:40:00] => 11:40 - 12:30 [12:30:00] => 12:30 - 13:20 [13:20:00] => 13:20 - 14:10 [14:10:00] => 14:10 - 15:00 [15:00:00] => 15:00 - 15:50 [15:50:00] => 15:50 - 16:40 )

php arrays time intervals
1个回答
-1
投票

以下内容可能会对您有所帮助:

$values = array_values($arr); // store all values in array
$count = 0;
foreach ($arr as $key => $value) {
    $count++;
    $nextVal = $values[$count] ?? ''; // check if next value exists
    $arrNew[$key] = $value . "-" . $nextVal;
}

注意:空合并运算符(??)已在PHP7中添加。对于PHP版本<7,请使用常规三进制:$nextVal = isset($values[$count]) ? $values[$count] : '';

工作demo

© www.soinside.com 2019 - 2024. All rights reserved.