奇怪的增加查询结果一段时间

时间:2013-04-16 14:09:25

标签: php sql while-loop increment

我不明白为什么'$ taille'数组的结果开始于键[1]而不是键[0]?所以它显示3个结果而不是4个(隐藏第一个结果) )...

<?php 
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();

$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
    $i++;
    $taille[$i] = $donnees['size'];
    $numb_taille['total'] = $i;
}
$total = $numb_taille['total'];

echo '<pre>';
print_r ($taille);
echo '</pre>';

$req->closeCursor();
?>

哪个给出了

ARRAY
(
    [1] => S
    [2] => M
    [3] => L
)

而不是

ARRAY
(
    [1] => XS
    [2] => S
    [3] => M
    [4] => L
)

任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

PHP数组从0开始,所以您需要做的就是将i++向下移动,直到您完成使用该索引中的数据为止

<?php 
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();

$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
    $taille[$i] = $donnees['size'];
    $numb_taille['total'] = $i;
    $i++; //iterate after your calculations are done
}
$total = $numb_taille['total'];

echo '<pre>';
print_r ($taille);
echo '</pre>';

$req->closeCursor();
?>

答案 1 :(得分:0)

这是因为在将i用作新数组项的键之前递增$ i。

在while循环结束时执行增量。

答案 2 :(得分:0)

问题是你还有一个额外的

$donnees = $req->fetch();
填充$taille的循环前的

语句。因此,第一行中的数据被提取但未存储在数组中。