【问题标题】:Group results from foreach by a var from the string通过字符串中的 var 对 foreach 的结果进行分组
【发布时间】:2015-11-04 18:24:05
【问题描述】:

我的查询得到以下结果:

技术1

  • p1 一些文字

技术2

  • p22 一些文字

技术3

  • p1 一些其他文字

技术2

  • p52 一些文字

技术2

  • p62 一些文字

我想按 Tech# 对结果进行分组,结果将是

技术1

  • p1 一些文字

技术2

  • p22 一些文字

  • p52 一些文字

  • p62 一些文字

技术3

  • p1 一些其他文字

这是使用的代码:

$vars = new WP_Query( array( 'category_name' => 'actualite'));
        while ( $vars->have_posts() ) : $vars->the_post();
        $child_posts = types_child_posts("contenu");    
        foreach ($child_posts as $child_post) :
                    if($child_post->fields['theme']=='A'):
                    $technique =$child_post->fields['f1'];
                        if (@$lastTechnique != $technique):
                            print "<strong>".$technique."</strong><br>";
                        endif;                              
                            echo "- ".$child_post->fields['f2']." Some text : ".$child_post->fields['f3']." (some text : ";the_title();echo ")<br>";
                    else:
                        echo "";
                    endif;
                endforeach;
        endwhile;

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:
    $vars = new WP_Query( array( 'category_name' => 'actualite'));
    $techniques = [];
    while ( $vars->have_posts() ) : 
        $vars->the_post();
        $child_posts = types_child_posts("contenu");    
        foreach ($child_posts as $child_post) :
            if($child_post->fields['theme']=='A'):
                $technique =$child_post->fields['f1'];
                if (!isset($techniques[$technique]))
                {
                    $techniques[$technique] = [];
                }
                $techniques[$technique][] = "- ".$child_post->fields['f2']." Some text : ".$child_post->fields['f3']." (some text : " . get_the_title() . ")<br>";
            endif;
        endforeach;
    endwhile;
    foreach ($techniques as $technique=>$childTexts):
        print "<strong>".$technique."</strong><br>";
        foreach (array_unique($childTexts) as $childText):
            print $childText;
        endforeach;
    endforeach;
    

    【讨论】:

    • 亲爱的 Evan,感谢您的试用。它返回的结果比预期的要多得多,因为许多结果行在您的输出中被复制了多次。代码中放置foreach的地方一定有问题。
    • 现在可以给我看看输出了吗?你用的是第一个还是第二个例子?
    • 我使用了这两个示例并删除了 the_title()。即使这样,结果也会被复制多次。
    • 抱歉,您对 foreach 的放置是正确的。现在已经修好了。
    • 埃文,你摇滚!!!你让我今天一整天都感觉很好。非常感谢。你有 WordPress 的经验吗?我试图只获取自定义字段“主题”值为“A”的帖子(post_type = post)。自定义字段“主题”是自定义帖子“contenu”的一部分,它是 post_type=post 的子项。自定义字段“主题”是名为 Contenudata (group_id=750) 的自定义字段组的一部分。上面的代码是一种解决方法,1)从 post_type=post 获取所有帖子,2)检查具有“theme”=“A”的帖子。这种解决方法很繁重。知道如何直接选择具有自定义字段“主题 =”A”的帖子。?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2019-08-06
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多