2015-10-04 2 views
1

У меня есть следующий код PHP, который тянет сообщения из определенной категории и отображает их в неупорядоченном списке.Сплит результаты foreach в 2 неупорядоченных списках с PHP

Я хотел бы изменить это, чтобы он отображал 5 <li> в одном <ul>, а затем создает новый <ul> еще на 5 и так далее.

Вот мой существующий код:

<?php 
$args = array('posts_per_page' => 15, 'offset'=> 1, 'category' => $cat_ID); 
$myposts = get_posts($args); 
foreach ($myposts as $post) : setup_postdata($post); 
?> 
    <li> 
     <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
    </li> 
<?php 
endforeach; 
wp_reset_postdata(); 
?> 
+1

Любые вопросы/вопросы с ответами? – chris85

+0

@ chris85 Мне очень жаль. Я действительно отработал свой ответ и вскоре опубликую его здесь. Я не мог получить другие 2 Ответы для работы :) – michaelmcgurk

ответ

0

Вот грубый пример использования modulus operator на каждую 5-ю итерацию.

$myposts = array(1,2,3,4,5,6,7,8,9,10,11); 
$output = '<ul>' . "\n"; 
foreach ($myposts as $count => $post) { 
    if ($count > 1 && $count % 5 == 0) { 
     $output .= '</ul><ul>' . "\n"; 
    } 
    $output .= '<li>' . $post . '</li>' . "\n" ; 
} 
rtrim($output, '</ul><ul>' . "\n"); //if it was the tenth iteration we don't want to open another ul 
echo $output . '</ul>' . "\n"; 

Выход:

<ul> 
<li>1</li> 
<li>2</li> 
<li>3</li> 
<li>4</li> 
<li>5</li> 
</ul><ul> 
<li>6</li> 
<li>7</li> 
<li>8</li> 
<li>9</li> 
<li>10</li> 
</ul><ul> 
<li>11</li> 
</ul> 
1

Другой способ сделать это с помощью array_chunk, например:

$myposts = [1,2,3,4,5,11,22,33,44,55,111,222,333,444]; 

foreach (array_chunk($myposts, 5) as $posts) { 
    echo "<ul>\n"; 
    foreach ($posts as $post) { 
     echo '<li>' . $post. '</li>'. "\n"; 
    } 
    echo "</ul>\n\n"; 
} 

Выходы:

<ul> 
<li>1</li> 
<li>2</li> 
<li>3</li> 
<li>4</li> 
<li>5</li> 
</ul> 

<ul> 
<li>11</li> 
<li>22</li> 
<li>33</li> 
<li>44</li> 
<li>55</li> 
</ul> 

<ul> 
<li>111</li> 
<li>222</li> 
<li>333</li> 
<li>444</li> 
</ul> 
Смежные вопросы