在PHP中迭代一个foreach循环并用str_replace替换一个计数器占位符

时间:2014-06-06 08:33:18

标签: php foreach count str-replace placeholder

这与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...

我也尝试了一些嵌套循环,但运气不佳。

enter image description here

1 个答案:

答案 0 :(得分:0)

我试过这个用于检查目的:

<?php
   function get_some_images( $args = "" ) {
   $images=[1,2,3];
// $images is an array of images from the curren post
    $i = 1;
  foreach($images as $image) {
    $before_img='<div class="img-%d">';
   $after_img='</div>';
    // Here's the tricky bit
    $before_img = str_replace('%d', $i, $before_img);
    $output .= $before_img . $image . $after_img;
   $i++;
   }
    var_dump($output);
    return $output; 
  }

  get_some_images($args);


  ?>

它产生了这个:                      <div class="img-1">1</div> <div class="img-2">2</div> <div class="img-3">3</div>

你可以去:http://www.compileonline.com/execute_php_online.php然后在激活这段代码后(在php标签中)...检查输出将显示你这个div结构..希望它有帮助..干杯!