如果找不到值,则 Foreach 不返回
Foreach not returning if value not found
foreach
如果没有找到,似乎会跳过元素。如果找不到,有没有办法强制它成为 return 备份值?我尝试使用 coalesce
无济于事...如果找到,它将 return period
,否则,跳过它并继续检查下一个元素。
$periods = ['October 2021', 'November 2021', 'December 2021'];
foreach ($periods as $k=>$p) {
$test = $mysqli->query("select coalesce(period, '$p') as period, coalesce(match_date, 'not found') as match_date from table where period = '$p'");
while($row = mysqli_fetch_array($test)) {
echo $row['period']. '-'. $row['match_date']. '<br>' ;
}
}
首先创建一个 table 然后插入所有带有 foreach
的句点
$reference = $mysqli->query("create temporary table reference (period varchar(15), match_date datetime); ");
foreach ($periods as $k=>$p) {
$insert = $mysqli->query("insert into reference (period)
values ('$p')");
}
然后我使用 left join
和 coalesce
$reference2 = $mysqli->query("select ref.period as period, coalesce(tb.match_date, 'not found') as match_date
FROM reference as ref
LEFT JOIN table as tb
ON ref.period = tb.period");
foreach
如果没有找到,似乎会跳过元素。如果找不到,有没有办法强制它成为 return 备份值?我尝试使用 coalesce
无济于事...如果找到,它将 return period
,否则,跳过它并继续检查下一个元素。
$periods = ['October 2021', 'November 2021', 'December 2021'];
foreach ($periods as $k=>$p) {
$test = $mysqli->query("select coalesce(period, '$p') as period, coalesce(match_date, 'not found') as match_date from table where period = '$p'");
while($row = mysqli_fetch_array($test)) {
echo $row['period']. '-'. $row['match_date']. '<br>' ;
}
}
首先创建一个 table 然后插入所有带有 foreach
$reference = $mysqli->query("create temporary table reference (period varchar(15), match_date datetime); ");
foreach ($periods as $k=>$p) {
$insert = $mysqli->query("insert into reference (period)
values ('$p')");
}
然后我使用 left join
和 coalesce
$reference2 = $mysqli->query("select ref.period as period, coalesce(tb.match_date, 'not found') as match_date
FROM reference as ref
LEFT JOIN table as tb
ON ref.period = tb.period");