duanjianxi8439 2013-02-12 21:06
浏览 18
已采纳

Foreach循环不比较[关闭]

I am somewhat of a programming noob, and i was stuck with an issue trying to echo out only a few items of my array instead of all the items in the array.

So what i have is a products.php file that contains my array $products, i am now trying to call this array from my index page, and i want to not only call the array, but to have the products in the array to list the last 4 products instead of all of them.

so now in my index.php i have created this code:

$total_products = count($products);
$position = 0;
$list_view_html = "";
foreach($products as $product_id => $product) {
$position = $position + 1;
if($total_product - $position < 4){
$list_view_html = $list_view_html . get_list_view_html($product_id,$product);
}
} 
echo $list_view_html;

now when i save and load the webpage, i still see all the products listed and not the 4 i should be seeing.

from what i understand, i am counting the products in the array, starting the loop at 0, looping through the array and then increment up the count +1. i then am stating that if the products in the loops position is less than the 4 items i want to be shown.

i know the code might not be the best way efficiency wise, or that it has certain critiques. I appreciate all the help, but i just need to figure out why i cant get this to work.

any help is appreciated, the less condescending the better.

thanks guys

  • 写回答

2条回答 默认 最新

  • dongzai5181 2013-02-12 21:08
    关注

    This is a typo. Change the if to:

    if($total_products - $position < 4){
    

    Note that the var's name is $total_products . You are using $total_product without the 's' and the end.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b