如何爆炸,而数组与逗号在ACF中继器(PHP)


How explode while array with commas in ACF Repeater (PHP)

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)的子字段,获取存储在字段jobtitle中的值。但它像Medicine Engineering Geography一样回响,我需要Medicine, Engineering, Geography。我发现了很多使用foreach的方法,但没有一个到while循环。

内爆应该可以工作:

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;
}

使用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;
}

我找到了一个方法。不确定它是否正确,使用两个"while",但它正在工作:

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——;)。如果没有,就在路上加逗号,然后继续前进……如果是(循环结束),一个点。

我不知道这是不是一个好的逻辑,也许我的大脑累了,有其他更干净的方法。但至少可以工作!