用Timber(twig)和Wordpress获取数组

时间:2016-12-30 09:44:25

标签: php arrays wordpress twig timber

我想用Timber(twig)和Wordpress创建一个字典。

我逐字逐句获取数组,但我需要生成一个字母列表:A - B - C - D ......

$query = new WP_Query(array('post_type' => 'lexique', 'posts_per_page' => -1));

$by_letter = array();
    while( $query->have_posts() ) { $query->the_post();
    $letter = substr($post->post_name, 0, 1);
    if (! isset($by_letter[$letter]) ) $by_letter[$letter] = array();
    $by_letter[$letter][] = $post;
}

if (!empty($by_letter)) {
    ksort($by_letter);
}

$context['query_lexique'] = $by_letter;

所以我需要在第一个字母[a] [b]中加注:

Array
(
    [a] => Array
        (
            [0] => WP_Post Object
                (
                    [ID] => 239
                    [post_author] => 1
                    [post_date] => 2016-12-29 14:22:03
                    [post_date_gmt] => 2016-12-29 13:22:03
                )

            [1] => WP_Post Object
                (
                    [ID] => 238
                    [post_author] => 1
                    [post_date] => 2016-12-29 14:21:34
                    [post_date_gmt] => 2016-12-29 13:21:34
                )

        )

    [b] => Array
        (
            [0] => WP_Post Object
                (
                    [ID] => 241
                    [post_author] => 1
                    [post_date] => 2016-12-29 16:34:28
                    [post_date_gmt] => 2016-12-29 15:34:28
                )

            [1] => WP_Post Object
                (
                    [ID] => 240
                    [post_author] => 1
                    [post_date] => 2016-12-29 16:34:07
                    [post_date_gmt] => 2016-12-29 15:34:07
                )

        )

)

如何让每封信生成我的清单?

1 个答案:

答案 0 :(得分:2)

{% for letter, posts in query_lexique %}
    <h1>{{ letter }}</h1>
    {% for post in posts %}
        ...
    {% endfor %}
{% endfor %}