看看這對你的作品。這是基於我在這裏給出的另一個答案。你循環的日子,每天積累與以前相同的價格在一個數組中。每當循環檢測到價格變化時,就會創建一個新數組,等等。
<?php
$values[] = ["2017-09-01", "158.00"];
$values[] = ["2017-09-02", "158.00"];
$values[] = ["2017-09-03", "158.00"];
$values[] = ["2017-09-04", "158.00"];
$values[] = ["2017-09-10", "175.00"];
$values[] = ["2017-09-11", "175.00"];
$values[] = ["2017-10-20", "158.00"];
$values[] = ["2017-10-21", "158.00"];
$values[] = ["2017-10-22", "159.00"];
$values[] = ["2017-10-23", "152.00"];
$values[] = ["2017-10-24", "152.00"];
$ult = null;
$currentRange = [];
$ranges = [];
foreach ($values as $fecha) {
$day = $fecha[0];
$price = $fecha[1];
if ($ult === null) {
$currentRange = [
"price" => $price,
"days" => [$day]
];
}
else {
if ($price === $ult) {
$currentRange["days"][] = $day;
}
else {
$ranges[] = $currentRange;
$currentRange = [
"price" => $price,
"days" => [$day]
];
}
}
$ult = $price;
}
$ranges[] = $currentRange;
$rangesString = [];
foreach ($ranges as $range) {
$str = $range["days"][0];
if (count($range["days"]) > 1) {
$str .= " - ".$range["days"][count($range["days"]) - 1];
}
$str .= ": ".$range["price"];
$rangesString[] = $str;
}
echo (implode("<br>", $rangesString));
/* results:
2017-09-01 - 2017-09-04: 158.00
2017-09-10 - 2017-09-11: 175.00
2017-10-20 - 2017-10-21: 158.00
2017-10-22: 159.00
2017-10-23 - 2017-10-24: 152.00
*/
Demo
這是因爲你想在下一次價格恢復到158一個新的日期對一個艱難的一個;所以在OP中你有三個結果,即使只有兩個價格。你認爲如何解析PHP中的結果? – BeetleJuice
事實上,即使在不同的年份,我也有更多相同的價格。 它僅用於打印出不同時期的價格,可能會在同一年重複,可能不會。 – Helenp