【问题标题】:Print only the array values - PHP仅打印数组值 - PHP
【发布时间】:2019-03-17 20:17:12
【问题描述】:

我在 WP 循环中有以下代码

<?php
                // Get the selected taxonomies for the post type
                $terms = get_the_terms( get_the_ID(), 'course_type' );
                $classes = array();
                if ( $terms && ! is_wp_error( $terms ) ){
                    foreach ( $terms as $term) {
                        $classes[] = $term->slug;
                    }
                }
                ?>

我要做的是只打印 WP_Term 对象 slug 以在类中使用。

<div class="courses-search-result standout-box-shadow <?php print_r( $classes ); ?>">

现在,我已经让它工作到一定程度并在类中打印一个值 - 但它也在打印数组结构:

class="courses-search-result standout-box-shadow cilex-clearfix Array
(
    [0] => apprenticeship
)
"

我是否接近使用我的 PHP 获得正确的代码?我现在对这门语言的了解还很基础,因此我们将不胜感激。

【问题讨论】:

标签: php arrays wordpress


【解决方案1】:

我建议将implode()PHP short echo tag 结合使用(即&lt;?= - 在启用short_open_tag 配置设置的PHP 5.4+ 或更早版本中可用):

<div class="courses-search-result standout-box-shadow <?= implode(' ', $classes ); ?>">

【讨论】:

    【解决方案2】:

    print_r 是一个用于调试的函数,而不是格式化输出。

    实现你想要的最简单的方法是使用implode,它将数组的值组合成一个字符串;然后echo 显示字符串。

    <div class="courses-search-result standout-box-shadow <?php echo implode(' ', $classes); ?>">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      相关资源
      最近更新 更多