ACF Repeater(PHP)中带逗号的数组如何爆炸

时间:2014-06-21 01:25:03

标签: php wordpress while-loop explode advanced-custom-fields

ACF Repeater是WordPress的一个插件,用于创建自定义字段。我需要用逗号分隔值,但是如何在while循环中执行它?

这是代码:

if( get_field('jobtitles') ) {
    echo '<strong>Jobs: </strong>'; 
        while ( have_rows('jobtitles') ) : the_row();
        echo '<span>'. get_sub_field('jobtitle') .'</span> ';   
        endwhile;
}

the_row遍历主要字段(job titles)的子字段,并在fieds jobtitle中获取值存储。但它像Medicine Engineering Geography那样回应,我需要Medicine, Engineering, Geography。我发现有很多方法可以使用foreach,但没有使用while循环。

3 个答案:

答案 0 :(得分:1)

Implode应该有效:

if( get_field('jobtitles') ) {
    echo '<strong>Jobs: </strong>'; 
    while ( have_rows('jobtitles') ) : the_row();
     $array[] = get_sub_field('jobtitles'); 
    endwhile;
    $foo = implode(', ', $array);

    echo $foo;
}

答案 1 :(得分:0)

使用explodeimplode会有效吗?

if( get_field('jobtitles') ) {
    echo '<strong>Jobs: </strong>'; 
        while ( have_rows('job titles') ) : the_row();
          $jobtitle_array = explode(' ', get_sub_field('jobtitle'); 
          echo '<span>' . implode(', ', $jobtitle_array)  .'</span> ';   
        endwhile;
}

答案 2 :(得分:0)

我发现了一种方法。不确定它是否合适,使用两个“whiles”,但它正在工作:

if( get_field('jobtitles') ) {
    $num_rows = 0;
        while ( have_rows('jobtitles') ) : the_row();
        $num_rows++;
        endwhile;

    echo '<strong>Jobs: </strong>';
        while ( have_rows('jobtitles') ) : the_row();
        $num_rows--;
        echo '<span>'. get_sub_field('jobtitle') .'</span>';
        if ( $num_rows == 0 ) { echo '.'; }
        else { echo ', '; }
        endwhile;
}

第一个while在var $ num_rows上加1。因此,如果我有10个自定义字段,它将以$ num_rows = 10结束循环。第二个回显值,并在每个循环上检查行数是否减少($ num_row--;)。如果没有,请在路上逗号并继续......如果是(循环结束),则为点。

我不知道这是不是一个好的逻辑,也许我的思绪已经累了,还有其他更清洁的方法。但至少有效!