How to count an array content and assign number position with php

白昼怎懂夜的黑 提交于 2020-01-07 08:00:33

问题


am working on a website project in which i fetch array from my database and use foreach statement to output its contents. I want use php script to count how many items are in the array and assign number position to each item so that if the number position of the first item is an odd number i will apply css float:left style to it but if its even number it will float:right

any help please??. thank you.


回答1:


Use the modulus operand:

<?php foreach ( $array as $index => $item ): ?>
    <div class="<?php echo $index % 2 ? 'even' : 'odd'; ?>"></div>
<?php endforeach; ?>

Then just use those class names in your CSS:

.odd {  float: left }
.even { float: right }



回答2:


CSS3 has nice features (.list:nth-child(odd) {float:left;} .list:nth-child(even) {float:right;} ), but beware that this will not work on many browsers (ie8 and below, older firefox, etc) .. at least every user with WinXP+IE will see just a normal list without the different colors.

jQuery (also noted here) can also select with $('.xy:odd').css({'float':'left'}); , but if you are not using jQuery in your project its just a big (90kb jQuery library) overhead. Performance is also better if going with php.

So you better go with php and the modulo operand (if $count % 2), see Joseph Silber's answer here.




回答3:


I think you can also use jquery with :odd selector.




回答4:


You can do it with css only:

.list:nth-child(odd) {float:left;}
.list:nth-child(even) {float:right;}


来源:https://stackoverflow.com/questions/14343073/how-to-count-an-array-content-and-assign-number-position-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!