如何回显 php 数组值

How to echo php array values

出于某种原因,我的 for 循环无法正常工作,实际上它破坏了页面。

你能看出我哪里做错了吗

<?php 
    $args = array(
        'post_type'         => 'property',
        'posts_per_page'    => -1,
        'meta_key'          => 'property_status',
        'meta_value'        => 'For Sale'
    );

    $query = new WP_Query($args);
?>


<?php if( $query->have_posts() ): ?>
    <?php while( $query->have_posts() ): $query->the_post(); ?>
        <?php $town_array[] = get_field('town'); ?>
    <?php endwhile; ?>
    <?php 
        wp_reset_query();

        $towns = array_unique($town_array);

        for ($i = 0; $i < count($towns); $i++){
            echo "<li>"$towns[$i]"</li>"; 
        }
    ?>
<?php endif; ?>

您必须在 echo 中进行字符串连接。如下更改您的脚本:

 for ($i = 0; $i < count($towns); $i++){
            echo "<li>".$towns[$i]."</li>"; 
        }

替换

echo "<li>"$towns[$i]"</li>"; 

echo "<li>".$towns[$i]."</li>"; 

这样更简单易读:

<?php while( $query->have_posts() ): $query->the_post(); ?>
<li><?php the_field('town'); ?></li>
<?php endwhile; ?>