仅在 if 语句循环中显示第一项



此代码:

require_once 'feed.php';
$title = 'Ev 134';
ob_start();
foreach(Feed('example.url') as $f ) {
if (strpos($f->title, $title) !== false) {
$green_color    = 'green';
$orange_color   = 'orange';
$red_color      = 'red';
$closed_text    = 'closed';
$maintenance_text   = 'maintenance';
$exception_text = 'could be';
if (strpos($f->title, $title) !== false){
if(strpos($f->description, $closed_text) !== false){
echo (strpos($f->description, $exception_text) === false) ?
'<span style="color:'.$red_color.';text-shadow: 2px 2px #a50000;">closed</span>' :
'<span style="color:'.$green_color.'">Open</span>' ;
} else if(strpos($f->description, $maintenance_text) !== false){
echo (strpos($f->description, $exception_text) === false) ?
'<span style="color:'.$orange_color.'">maintenance</span>' :
'<span style="color:'.$green_color.'">Open</span>' ;
} else {
echo '<span>Open</span>';
}
}
}
}
$status = ob_get_contents();
ob_end_clean();
echo $status;

从道路输出当前天气报告。吃掉打开/关闭或维护。

我的问题:

可能会有可能导致我不想要的openopenmaintenanceopen输出。

我试过:

if ($status = 'OpenOpen'){
$status = 'Open';
}

但是在所有可能的情况下,它既复杂又混乱+它不能很好地工作。

我想要的:如果有多个报告,只显示第一个并在文本后面加上*。

任何帮助将不胜感激!

此代码进行了一些更改。

这不使用输出缓冲,而只是将值设置为$status。 这允许您检查是否已设置以前的值并将*添加到末尾,或者如果它到达循环的末尾并且$status仍然为空,则可以设置打开的文本。

我还将静态文本分配移到了循环之外,因为您不需要每次都设置它们。

最后,您有两次if (strpos($f->title, $title) !== false),因此这删除了...

$green_color    = 'green';
$orange_color   = 'orange';
$red_color      = 'red';
$closed_text    = 'closed';
$maintenance_text   = 'maintenance';
$exception_text = 'could be';
$status = "";
$records = 0;
foreach(Feed('https://www.vegvesen.no/trafikk/xml/savedsearch.rss?id=604') as $f ) {
$records++;
if (strpos($f->title, $title) !== false) {
if(strpos($f->description, $closed_text) !== false){
// If no previous value, set main text,otherwise add *
if ( empty($status) )   {
$status = (strpos($f->description, $exception_text) === false) ?
'<span style="color:'.$red_color.';text-shadow: 2px 2px #a50000;">closed</span>'
: '<span style="color:'.$green_color.'">Open</span>' ;
}
else    {
$status .= "*";
}
} 
else if(strpos($f->description, $maintenance_text) !== false){
if ( empty($status) )   {
$status = (strpos($f->description, $exception_text) === false) ?
'<span style="color:'.$orange_color.'">maintenance</span>' :
'<span style="color:'.$green_color.'">Open</span>' ;
}
else    {
$status .= "*";
}
}
}
}
// If still empty, say open
if ( empty ( $status ) ){
$status = '<span>Open</span>';
if ( $records > 0 ) {
$status.="*";
}
}
echo $status;

在设置橙色和红色部分时,您可以删除(strpos($f->description, $exception_text) === false)的测试,如果文本中有$exception_text,则忽略该项目。

最新更新