foreach php逻辑问题

时间:2012-08-11 16:11:46

标签: php

我在购物车db中有4条记录。我得到了结果:4444。如何将结果更改为1234?

查看:

$i = 0; 
foreach($carts AS $cart) {
    $x = $i+1;
    echo $x;
}

控制器:

function confirm() {
    $orders = $this->data;
    $sessionId = $this->passedArgs['ct_session_id'];
    $this->set('data', $sessionId );
    $carts = $this->Cart->find(
        'all', 
        array('conditions' => array('Cart.ct_session_id' => $sessionId), 'recursive' => 1)
    );
    $this->set(compact('carts', 'orders'));         
}

3 个答案:

答案 0 :(得分:3)

<?php
$i = 0; 
foreach($carts as $cart) {
    $i++;
    echo $i;
}
?> 

答案 1 :(得分:1)

我想你每次执行这条指令都要增加$ i,所以你必须写: $x = ++$i;

答案 2 :(得分:0)

<?php
$count = count($carts);
for($i=0; $i<$count; $i++)
{
  echo $i."</br>";
}

?>