回显数组中的每个变量


Echo every variable in an array

我正在尝试删除空格并将其替换为数组中每个变量中的"-"。但是我只得到数组的最后一个变量。

我的代码:

<ul class="gap-items">
<?php 
    while ($query->have_posts()): 
        $query->the_post(); 
        $post_type = get_post_type( get_the_ID() );   
        $key = 'field_5208f1f811702';
        $value = get_field($key);
        var_dump($value);
        foreach ($value as $label) {
            $label = strtolower($label);
            $label = preg_replace("/[^a-z0-9_'s-]/", "", $label);
            //Clean up multiple dashes or whitespaces
            $label = preg_replace("/['s-]+/", " ", $label);
            //Convert whitespaces and underscore to dash
            $label = preg_replace("/['s_]/", "-", $label);
            var_dump($label);
        }
?>
        <!-- Loop posts -->     
        <li class="item <?php echo $post_type ?> <?php echo $label ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">

所以$value是一个数组。对于每个变量,我都会删除空格并将其替换为破折号。我需要回显 foreach 函数外部的每个变量。我也试图先内爆变量,但没有结果。怎么做?谢谢!

编辑:第一个var_dump($value);给了我一个数组,如下所示: array(2) { [0]=> string(8) "Option 3" [1]=> string(8) "Option 4" }

var_dump($label)给出: string(8) "option-3" string(8) "option-4"

我想回应一下:选项 3 选项 4

你只得到最后一个,因为你的回声线:

<li class="item <?php echo $post_type ?> <?php echo $label ?>"></li>

放置在您的 foreach 循环之后。因此,它使用为$label$post_type设置的最后值。尝试将其放在循环中,以便每次循环列表时都会生成回声。

你最终应该得到如下的东西:

$value = get_field($key);
foreach ($value as $label) {
    $label = strtolower($label);
    $label = preg_replace("/[^a-z0-9_'s-]/", "", $label);
    //Clean up multiple dashes or whitespaces
    $label = preg_replace("/['s-]+/", " ", $label);
    //Convert whitespaces and underscore to dash
    $label = preg_replace("/['s_]/", "-", $label);

    echo "<li class='"item $post_type $label'"></li>";
}

您过早关闭了 foreach 循环:

$value = get_field($key);
foreach ($value as $label) {
$label = strtolower($label);
$label = preg_replace("/[^a-z0-9_'s-]/", "", $label);
//Clean up multiple dashes or whitespaces
$label = preg_replace("/['s-]+/", " ", $label);
//Convert whitespaces and underscore to dash
$label = preg_replace("/['s_]/", "-", $label);

echo "<li class='item $post_type $label'></li>"
}

使用 str_replace 函数,它接受一个字符串并替换所有出现的情况。

str_replace(' ','-',$label)

http://php.net/manual/en/function.str-replace.php

您可以使用

print_r() .这将打印包含键和值的整个数组。

所以在foreach之后,你会写:

print_r($value);

http://php.net/manual/en/function.print-r.php