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.