我正在尝试生成一个具有 2 个值日期和成本的单个字符串
如果用户选择开始日期 1/1/2025 和结束日期 3/1/2025 并且成本为 250,我希望构建一个字符串,如下所示。
"20250101":250,"20250102":250
我正在使用以下代码。
$pricepern = 250;
$period = new \DatePeriod(
new \DateTime($start_date),
new \DateInterval('P1D'),
new \DateTime($end_date));
foreach ($period as $key => $value) {
$individualdays = '"'.$value->format('Ymd').'":'.$pricepern.',';
echo $individualdays; // It works in here
}
echo $individualdays; // It only provides the last value out here
如果能帮助理解我如何在 foreach 之外生成单个字符串,我将不胜感激。我确实尝试在外面内爆,但它表明该值不是数组。
将所有
date:cost
对放入一个数组中,并使用 implode()
将它们与逗号分隔符组合起来。
$days_array = array_map(fn($value) => '"'.$value->format('Ymd').'":'.$pricepern, $period);
$individual_days = implode(',', $days_array);
echo $individual_days;
要构建包含所有日期成本对的单个字符串,您可以在循环内连接每个
$individualdays
字符串,然后删除结尾的逗号。这里有一个方法可以做到:
$start_date = '2025-01-01';
$end_date = '2025-03-01';
$pricepern = 250;
$period = new \DatePeriod(
new \DateTime($start_date),
new \DateInterval('P1D'),
new \DateTime($end_date)
);
$fullString = ''; // Initialize an empty string to hold the full result
foreach ($period as $key => $value) {
$individualdays = '"' . $value->format('Ymd') . '":' . $pricepern . ',';
$fullString .= $individualdays; // Concatenate each day string
}
// Remove the trailing comma
$fullString = rtrim($fullString, ',');
echo $fullString;
此代码将生成所需的输出字符串,其中所有日期成本对连接在一起,并删除尾随逗号。