【问题标题】:How to set a variable separator如何设置变量分隔符
【发布时间】:2018-07-31 00:58:57
【问题描述】:

我有一个变量 $cameramodel,其中包含 wordpress 分类的术语元:

<?php 
function cameramodel() {
$terms = get_the_terms($post->ID, 'camera');
$result = "";
foreach ($terms as $term) {
    $term_id = $term->term_id;
    $result .= get_term_meta( $term_id, 'model', true );
}
return $result;
}

$cameramodel = cameramodel(); ?>

在前端我会回显$cameramodel

<?php echo $cameramodel; ?>

在某些情况下$cameramodel 包含多个值,但是当我回显$cameramodel 时,它们都出现在一行上,没有空格。我的问题是,如何在每个值之间进行分隔符?我希望每个值都在它自己的行上,并且我希望能够用“and”这个词来分隔它们。

例如,如果变量包含“一二三”它当前打印“onetwothree”,但我想要的是:

one and
two and
three

希望我说的很清楚。

谢谢!

【问题讨论】:

    标签: php wordpress variables separator


    【解决方案1】:

    如果您愿意稍微编辑该函数,我相信您会受益于使用数组,然后将其连接成一个字符串,并将您选择的分隔符作为参数传递:

    <?php 
        function cameramodel($delimiter) {
            # Get the terms.
            $terms = get_the_terms($post -> ID, "camera");
    
            # Create an array to store the results.
            $result = [];
    
            # Iterate over every term.
            foreach ($terms as $term) {
                # Cache the term's id.
                $term_id = $term -> term_id;
    
                # Insert the term meta into the result array.
                $result[] = get_term_meta($term_id, "model", true);
            }
    
            # Return the elements of the array glued together as a string.
            return implode($delimiter, $result);
        }
    
        # Call the function using a demiliter of your choice.
        $cameramodel = cameramodel(" and<br>");
    ?>
    

    当然,你可以在函数中嵌入你想要的分隔符作为implode的第一个参数,而不是作为参数传递。

    Here 是使用相同逻辑的示例。

    【讨论】:

    • 工作就像一个魅力。谢谢!我假设如果我想使用变量作为分隔符,我可以这样做吗? $cameramodel = cameramodel($variable);
    • 最后一件事,如果我这样做$cameramodel = cameramodel($variable); 有什么方法可以让我设置不同于字符串的 $variable 样式吗?例如,我可以将输出的字符串设置为粗体,而分隔符不设置为粗体吗?像这样:一个和两个和三个
    • 当然@AMerdaman。将$result[] = get_term_meta($term_id, 'model', true);这一行改为$result[] = "&lt;b&gt;" . get_term_meta($term_id, 'model', true) . "&lt;/b&gt;";
    • 现在我有这样的:&lt;h1 class=text&gt;&lt;?php echo cameramodel(" and&lt;br&gt;"); ?&gt;&lt;h1/&gt; 我在 h1 类上有几种样式。是否仍然可以以不同的方式设置分隔符?我尝试了("&lt;p&gt; and&lt;br&gt;&lt;p/&gt;"),但这也将&lt;p&gt; 样式应用于下一个输出行...
    • 你可以为所欲为。例如,制作分隔符:" &lt;span class = 'custom'&gt;and&lt;/span&gt;&lt;br&gt;" 并使用 CSS 为 .custom 类提供任何您想要的样式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2021-03-04
    相关资源
    最近更新 更多