我有一个包含数据的数组(ID号和与之关联的数据(。
数组中的项数始终是可变的且未知。
如果原始数组(不是切片(中有 2 个以上的项目,我想将此数组分成相等的两个相等的部分。
然后,我想创建两个独立的 UL 列表,其中包含生成的数组切片项目。如果原始数组中的项目总数为奇数,则第一个列表应再携带一个项目。
我想出了这个,但我确定我做错了......输出中显示的内容对于每个UL列表几乎相同,只是重新排序,而且在我的情况下,数字是奇数(如果我回显$items它会得到3.5(。
$panels = get_field('related_content');
$items = count($panels);
if ($items > 2) {
$split = $items / 2;
$firsthalf = array_slice($panels, $plit );
$secondhalf = array_slice($panels, 0, $plit);
echo '<div class="related-carousel"><ul>';
foreach($firsthalf as $post_object) :
printf('<li><a target="_blank" title="'.get_the_title($post_object->ID).'" href="'.get_permalink($post_object->ID).'"><span class="thumb">'.get_the_post_thumbnail($post_object->ID, 'smallest').'</span><span class="thumb-title"><h6>'.get_the_title($post_object->ID).'</h6></span></a><span>'.sg_get_the_excerpt().'</span></li>');
endforeach;
echo'</ul></div>';
echo '<div class="related-carousel"><ul>';
foreach($secondhalf as $post_object) :
printf('<li><a target="_blank" title="'.get_the_title($post_object->ID).'" href="'.get_permalink($post_object->ID).'"><span class="thumb">'.get_the_post_thumbnail($post_object->ID, 'smallest').'</span><span class="thumb-title"><h6>'.get_the_title($post_object->ID).'</h6></span></a><span>'.sg_get_the_excerpt().'</span></li>');
endforeach;
echo'</ul></div>';
}
else {
echo '<div class="related-carousel"><ul>';
foreach($panels as $post_object) :
printf('<li><a target="_blank" title="'.get_the_title($post_object->ID).'" href="'.get_permalink($post_object->ID).'"><span class="thumb">'.get_the_post_thumbnail($post_object->ID, 'smallest').'</span><span class="thumb-title"><h6>'.get_the_title($post_object->ID).'</h6></span></a><span>'.sg_get_the_excerpt().'</span></li>');
endforeach;
echo'</ul></div>';
}
您需要将
array_slice
的参数$plit
更改为$split
!打开有助于解决此类错误的错误报告总是很有用的:error_reporting(E_ALL)
.
您可能需要更改$split
变量,例如通过使用ceil()
,编辑:查看AndVla答案
认为你可以这样解决问题:
$split = ($items+1) / 2;
或
$split = ceil($items / 2);
tim 是对的,但是您可能也希望前半部分是数组的前半部分,而不是像现在这样反之亦然。这是因为切片参数是:$output = array_slice($input, $offset, $length);
。所以你需要像这样设置你的变量 $firsthalf = array_slice($panels, 0, $split);
$secondhalf = array_slice($panels, $split, $items);
干杯