我有以下数组:
array:37 [▼
"09:00" => Appointment {rows = 4}
"09:15" => ""
"09:30" => ""
"09:45" => ""
"10:00" => ""
"10:15" => ""
"10:30" => ""
"10:45" => ""
"11:00" => ""
"11:15" => ""
"11:30" => ""
"11:45" => ""
"12:00" => Appointment { rows => 2}
"12:15" => ""
"12:30" => ""
"12:45" => ""
]在$appointment内部有一个属性约会->工期,它是一个整数数据类型。
我想循环遍历数组,取“工期”的值,并在折叠空数组位置设置一个标志。示例:
array:37 [▼
"09:00" => Appointment {rows = 4}
"09:15" => "yes"
"09:30" => "yes"
"09:45" => "yes" //this is the fourth
"10:00" => ""
"10:15" => ""
"10:30" => ""
"10:45" => ""
"11:00" => ""
"11:15" => ""
"11:30" => ""
"11:45" => ""
"12:00" => Appointment { duration => 2}
"12:15" => "yes" //this is the second
"12:30" => ""
"12:45" => ""
]我做了这个:
$loops = 0;
$calendar = $calendar[0];
foreach ($calendar as $key => $appointment) {
if ($appointment) {
$loops = $appointment->rows;
} else {
for ($i = 0; $i < $loops; $i++) {
$calendar[$key] = 'ja';
}
$i = 0; $loops = 0;
}
}但我只得到一个标志,而不是期望的数字(持续时间)。
array:37 [▼
"09:00" => Appointment {#6930 ▶}
"09:15" => "ja"
"09:30" => ""
"09:45" => ""
"10:00" => ""
....我做错了什么?
发布于 2019-11-19 08:13:06
给你:
<?php
//BUILD ARRAY
$calendar = [
"09:00" => [],
"09:15" => "",
"09:30" => "",
"09:45" => "",
"10:00" => "",
"10:15" => "",
"10:30" => "",
"10:45" => "",
"11:00" => "",
"11:15" => "",
"11:30" => "",
"11:45" => "",
"12:00" => [],
"12:15" => "",
"12:30" => "",
"12:45" => ""
];
$calendar["09:00"]["Appointment"]["rows"] = 4;
$calendar["12:00"]["Appointment"]["rows"] = 2;
//END BUILD ARRAy
$loops = 0;
$appointment_index = -1;
foreach ($calendar as $key => $appointment) {
$current_index = array_search($key,array_keys($calendar)); // Get current index of $calendar array
if ($appointment) {
$appointment_index = $current_index; // Store appointment index
$loops = $appointment["Appointment"]["rows"]; // Get loops
}
if($current_index - $appointment_index < $loops ){ // Find the next N elemnts after $appointment->rows
if($current_index != $appointment_index) // Skip appointment element
{
$calendar[$key] = "Ja";
}
}
}
print_r ($calendar);
?>发布于 2019-11-19 06:54:56
我刚检查了你的输入和预期输出。几乎你已经做了,但你不需要改变与其他部分。
在这里,你应该使用“else if”而不仅仅是“else”。看见
else if($loops > 0) {
$calendar[$key] = "Yes";
$loops--;
}下面是获得预期输出的完整代码。
$calendar = array(
"09:00" => array('rows' => 4),
"09:15" => "",
"09:30" => "",
"09:45" => "",
"10:00" => "",
"10:15" => "",
"10:30" => "",
"10:45" => "",
"11:00" => "",
"11:15" => "",
"11:30" => "",
"11:45" => "",
"12:00" => array('rows' => 2),
"12:15" => "",
"12:30" => "",
"12:45" => "",
);
$loops = 0;
foreach($calendar as $key => $appointment) {
if(is_array($appointment)) {
$loops = $appointment['rows'] - 1;
} else if($loops > 0) {
$calendar[$key] = "Yes";
$loops--;
}
}
print_r($calendar);https://stackoverflow.com/questions/58927695
复制相似问题