如何使用php排除数组中的最后一行

问题描述 投票:2回答:1

我一直试图在手册中读到这一点,但基本上我有一个array,我试图扭转它并排除最后一项。所以我目前在我的阵列中有14个项目,我正在让它反转,它显示14-2。我的代码让它排除了最后一项。所以我认为它在技术上有效,但我实际上希望它输出为13-1。我尝试使用array_poparray_shift,但我不知道如何将它与array_reverse整合。

function smile_gallery( $atts ) {
    if( have_rows('smile_gallery', 3045) ):

    $i = 1;

    $html_out = '';

    $html_out .= '<div class="smile-container">';
        $html_out .= '<div class="fg-row row">';

            // vars
            $rows = get_field('smile_gallery', 3045);
            $count = count( get_field('smile_gallery', 3045) );

            $html_out .= '<div class="col-md-8">'; // col-md-offset-1
                $html_out .= '<div class="smile-thumbs">';

                foreach( array_reverse($rows) as $row) :

                // vars
                $week = "smile_week";
                $img = "smile_img";
                $caption = "smile_caption";

                // Do stuff with each post here
                if( $i < $count) :

                    $html_out .= '<div class="smile-thumb-container">';
                        $html_out .= '><h6>Week ' . $row["smile_week"] . '</h6></a>'; // smile thumb week  
                    $html_out .= '</div>'; // smile thumb container
                endif;

                $i++;

                endforeach;

                $html_out .= '</div>';
            $html_out .= '</div>';
        $html_out .= '</div>';
    $html_out .= '</div>'; // smile container

    endif;

    return $html_out;
}
add_shortcode( 'show_smiles', 'smile_gallery' );
php foreach count advanced-custom-fields
1个回答
3
投票

我正在阅读下面的问题,如果我错了,请纠正我。

我有一个数组,我试图扭转它并排除第一个和最后一个项目。

要做到这一点你知道你想要使用array_pop()array_shift()

<?php
//
$rows = get_field('smile_gallery', 3045);
$count = count($rows);

array_pop($rows);
array_shift($rows);

foreach (array_reverse($rows) as $row):
...

如果您想先倒退然后再进行操作,如果从两端移除物品则不需要。从foreach中取出array_reverse,然后进行操作。

<?php
// vars
$rows = get_field('smile_gallery', 3045);
$count = count($rows);

$rows = array_reverse($rows);

array_pop($rows);
array_shift($rows);

foreach ($rows as $row):
...

如果有帮助,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.