【问题标题】:How to filter specific element of an array in wordpress/php?如何在 wordpress/php 中过滤数组的特定元素?
【发布时间】:2019-08-11 17:51:05
【问题描述】:

我有一个如下所示的 php 代码,其中我添加了 Line#A 用于调试目的。

<div class="vidlist-main__meta cf">
    <?php

    //if ( has_excerpt() ) {the_excerpt();}
    $tags = get_the_tags( get_the_ID() );
    $cats = wp_get_post_categories( get_the_ID() );                // Line#Z
    echo '<pre>'; print_r($cats); echo '</pre>';                  // Line#A
    if ( $tags || $cats  ) : ?>    // Line#B
        <span class="archive-links">
            <?php
            \CPAC\Episodes\generate_markup_for_categories( $cats );    // Line#C
            \CPAC\Episodes\generate_markup_for_tags( $tags );          // Line#D
            ?>
        </span>
    <?php endif;?>
</div>

在添加 Line#A 时,我在不同情况下得到以下 o/p:

Case A:

Array
(
    [0] => 13085
    [1] => 13093
)

Case B:

Array
(
    [0] => 1
    [1] => 13087
)

Case C:

Array
(
    [0] => 1
    [1] => 13085
)

问题陈述:

我想知道我需要在 Line#Z 之后或 Line#Z 处添加什么代码,这样 Line#Z 只需要 [1]=&gt;13093

【问题讨论】:

  • 最简单的就是使用array_diff这样$cats = array_diff($cats , [1])然后你可以添加更多$cats = array_diff($cats , [1,2,3])等等$cats = array_diff(wp_get_post_categories( get_the_ID() ), [1]);
  • 如果你真的只想要so that Line#Z takes only [1]=&gt;13093,那么你可以用array_intersect做相反的事情就像这样$cats = array_intersect(wp_get_post_categories( get_the_ID() ), [13093]);
  • 我添加了这一行 $cats = array_diff(wp_get_post_categories( get_the_ID() ), [13093]); 现在所有内容都显示,不包括 13093。
  • 是的,这就是为什么我使用[1] 表示diff[13093] 表示intersect,而不是相反。 Diff 是 array1 与 array2 或 array1 中的所有项目不存在于其他数组中的差异,相交是相反的。 array1 中的所有项目(如果它们存在于任何其他参数中)。
  • @ArtisticPhoenix 你能给我解释一下吗? cmets 让我很困惑。

标签: php html arrays wordpress


【解决方案1】:

如果你想只保留一个(或几个值),你可以使用数组相交

<div class="vidlist-main__meta cf">
    <?php

    //if ( has_excerpt() ) {the_excerpt();}
    $tags = get_the_tags( get_the_ID() );
    $cats = array_intersect(wp_get_post_categories( get_the_ID() ), [13093]);                // Line#Z
    echo '<pre>'; print_r($cats); echo '</pre>';                  // Line#A
    if ( $tags || $cats  ) : ?>    // Line#B
        <span class="archive-links">
            <?php
            \CPAC\Episodes\generate_markup_for_categories( $cats );    // Line#C
            \CPAC\Episodes\generate_markup_for_tags( $tags );          // Line#D
            ?>
        </span>
    <?php endif;?>
</div>

最简单的例子是:

$a = [13085,13093];
print_r(array_intersect($a, [13093]));

输出

Array
(
    [1] => 13093
)

Sandox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2020-12-20
    • 2012-09-17
    • 1970-01-01
    相关资源
    最近更新 更多