PHP Foreach循环结束

时间:2016-02-18 09:00:00

标签: php foreach

如何在没有字符的情况下使最终的foreach实例结束?因为它代表$ var2的每个实例后跟一个字符。代码要遵循,提前谢谢。

foreach($tags as $var1 => $var2) {
    if($_SESSION[$var1]!="off")
    {
    include($var2);
    echo",";    
    //needs to include no , character on the last instance.
    }
    else
    {
    echo $var1;
    }
}

6 个答案:

答案 0 :(得分:1)

在您的foreach中,将foreach($tags as $var1 => $var2) { if($_SESSION[$var1]!="off") { include($var2); //needs to include no , character on the last instance. if(key(end($tags)) !== $var1) { echo","; } } else { echo $var1; } } 更改为以下内容:

echo ",";

执行此操作将通过将当前索引与if (end($tags) != $var2) { echo ","; } 数组的最后一个索引进行比较来检查您是否在最后一个索引中。单击key()以查看$tags函数上的PHP wiki。

答案 1 :(得分:0)

首先将所有回声插入到字符串中。 然后使用preg_replace函数删除“,”的最终实例:

onResume()

另一种方法是使用计数器:

$str = preg_replace('/\,$/', '', $str);

使用end()函数的另一种方法

$len = count($tags);  
$iter = 0;
foreach($tags as $var1 => $var2) {
        if($_SESSION[$var1]!="off")
        {
        include($var2);
        if($iter != $len-1)
          echo",";    
        //needs to include no , character on the last instance.
        }
        else
        {
        echo $var1;
        }
      $iter++;
    }

答案 2 :(得分:0)

使用此功能,您可以使用"line terminators"检索最后一个元素,并使用与当前密钥进行比较的end()获取密钥:

 input {
     file {
         path => "/var/log/nginx/*.log"
         type => "nginx"
         start_position => "beginning"
         sincedb_path=> "/dev/null"
     }
 }

 filter {
   if [type] == "nginx" {
     grok {
       patterns_dir => "/home/krishna/Downloads/logstash-2.1.0/pattern"
       match => { 
         "message" => "%{NGINX_LOGPATTERN:data}"
       }
     }
   }
   date {
     match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
     }
 }

 output {
   elasticsearch {
     hosts => [ "127.0.0.1:9200" ]
   }

   stdout { codec => rubydebug }
 }

答案 3 :(得分:0)

这将帮助你

 $result = '';
    foreach($tags as $var1 =>$var2) {
        $result .= $var2.',';
    }
    $result = rtrim($result,',');
    echo $result;

答案 4 :(得分:0)

尝试使用end()函数获取最后一项:

$last_item = end(array_keys($tags));
foreach($tags as $var1 => $var2) {
    if($_SESSION[$var1]!="off") {
    {
        include($var2);
        if($var1 !== $last_key) {
            echo",";    
        }
    //needs to include no , character on the last instance.
    }
    else
    {
        echo $var1;
    }
}

答案 5 :(得分:0)

检查最后一个元素和回显逗号(,)的一种方法

$numItems = count($tags );
$i = 0;
foreach($tags  as $var1 =>$var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
if(++$i != $numItems) {
echo ",";
}
}
else
{
echo $var1;
}
}