php在循环中递增变量的名称 [英] php Increment name of variable in a loop

查看:62
本文介绍了php在循环中递增变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想到了while循环,但找不到解决方法:

I thought of a while loop but cant find the way around this:

$foo1 = get_post_meta( $post->ID, '_item1', true );
if (!empty($foo1)){
    echo  ("<div class='$foo1'></div>"); 
}

$foo2 = get_post_meta( $post->ID, '_item2', true );
if (!empty($foo2)){
    echo  ("<div class='$foo2'></div>"); 
}

依次类推...直到我达到$ foo100和_item100 有什么想法要实现这一点,不要一遍又一遍地重复这4行吗?

And so on... for a hundred times until I reach $foo100 and _item100 Any idea to achieve this to not repeat these 4 lines over and over?

推荐答案

您不需要

You don't need variable variables for that, but just a for loop like this:

for( $i=1; $i<101; $i++ ) {
  $klass = get_post_meta( $post->ID, '_item' . $i, true );
  if( !empty($klass) ) {
     echo "<div class='$klass'></div>"; 
  }
}

只要以后不需要$fooX变量,此方法就起作用.如果需要它们,则必须使用提到的变量变量或数组来收集所有值.

This works as long as you do not need the $fooX variables later on. If you need them, you would have to use either mentioned variable variables or an array to collect all the values.

这篇关于php在循环中递增变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆