【问题标题】:How explode while array with commas in ACF Repeater (PHP)在 ACF 中继器 (PHP) 中使用逗号的数组时如何爆炸
【发布时间】:2014-06-21 01:25:03
【问题描述】:

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 循环。

【问题讨论】:

  • 您可以考虑将这个问题放在 WordPress 开发者网站上:wordpress.stackexchange.com
  • 我做到了,问题被标记为离题。

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


【解决方案1】:

内爆应该可以工作:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 不...不要返回任何东西。
    • 这在你的脚本中发生在哪里,But it echoes like this Medicine Engineering Geography
    • 与回声。实际上,它返回具有此值的自定义字段,因此它类似于:Medicine Engineering Geography.
    • 嗯。现在更有意义了。但我的头脑无法真正理解 API 逻辑。希望别人会。您可以考虑将这个问题放在 WordPress 开发者网站:wordpress.stackexchange.com
    • 谢谢。为了更清楚,have_rows 是一个布尔值。它的描述:“此函数检查该字段是否有任何要循环的数据行。这是一个布尔函数”。由于它不通过行,the_row 是工具。 “主要区别在于这个函数 (have_rows) 本身不会逐行遍历,因此要逐行遍历,还必须使用 the_row 函数。将 have_rows 和 the_rows 一起使用是为了让 have_posts 和 the_posts 感觉原生'WP 循环' 的想法。”
    【解决方案3】:

    我找到了办法。不确定它是否正确,使用两个“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--;)。如果不是,逗号在路上并继续……如果是(循环结束),一个点。

    我不知道这是否是一个好的逻辑,也许我的大脑很累,还有其他更清洁的方法。但至少有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2017-02-18
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多