【问题标题】:Iterate through a foreach loop in PHP and replace a counter placeholder with str_replace遍历 PHP 中的 foreach 循环并用 str_replace 替换计数器占位符
【发布时间】: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


    【解决方案1】:

    我试过这个是为了检查:

    <?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 结构..希望它有所帮助..干杯!

    【讨论】:

    • Alrite,如果$before_img='&lt;div class="img-%d"&gt;'; 在循环之外,它将无法工作,很有趣。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2010-10-24
    相关资源
    最近更新 更多