【发布时间】:2014-07-27 11:10:44
【问题描述】:
这与 WordPress 相关,但纯粹是 PHP 问题。
我有一个函数可以获取帖子中的所有图片,该函数让我可以控制图片前后的内容,即<figure> 和</figure>。
我有这样的功能:
function get_some_images( $args = "" ) {
$defaults = array(
'before_img' => '<figure>',
'after_img' => '</figure>',
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
// $images is an array of images from the curren post
$i = 1;
foreach($images as $image) {
// Pseudocode
$output .= $before_img . $image . $after_img;
$i++;
}
return $output;
}
用法:
$args = array(
'before_img' => '<div class="img">',
'after_img' => '</div>',
);
echo get_some_images($args);
到目前为止一切都很好。但是如果我想在before_img 中添加一个迭代计数器,我使用%d 作为占位符:
$args = array(
// Here's the difference, note the %d placeholder for iteration count
'before_img' => '<div class="img-%d">',
'after_img' => '</div>',
);
get_some_images($args);
我尝试过这样的事情:
$i = 1;
foreach($images as $image) {
// Here's the tricky bit
$before_img = str_replace('%d', $i, $before_img);
$output .= $before_img . $image . $after_img;
$i++;
}
但它不会迭代计数器,为所有迭代输出相同的数字:
<div class="img-1"><img></div>
<div class="img-1"><img></div>
<div class="img-1"><img></div>
...
如果我回显$i,它会正常迭代:
$i = 1;
foreach($images as $image) {
echo $i . ', ';
$i++;
}
// Outputs: 1, 2, 3...
我也尝试了一些嵌套循环,但运气不佳。
【问题讨论】:
标签: php foreach count str-replace placeholder