Php 如何从带有FOR循环的数组中提取特定的行索引号?

Php 如何从带有FOR循环的数组中提取特定的行索引号?,php,Php,我不确定我做错了什么。$numrows显示正在计数的行,但没有显示$Value1$Value2$Value3 您正在多次迭代索引: 第一次运行时: $i = 0; $Value1 = $result[0]['id']; $Value2 = $result[1]['id']; $Value3 = $result[2]['id']; 第二次运行时: $i = 1; $Value1 = $result[1]['id']; $Value2 = $result[2]['id']; $Value3

我不确定我做错了什么。$numrows显示正在计数的行,但没有显示$Value1$Value2$Value3


您正在多次迭代索引:

第一次运行时:

$i = 0;

$Value1 = $result[0]['id'];
$Value2 = $result[1]['id'];
$Value3 = $result[2]['id'];
第二次运行时:

$i = 1;

$Value1 = $result[1]['id'];
$Value2 = $result[2]['id'];
$Value3 = $result[3]['id'];
等等

你可以做:

for ($i = 0; $i < count($result); $i+=3)
查询将不适用于此for循环。你必须使用fetchAll。使用“singe batteur”优秀的计数代码,我们可以完成以下代码:

$sth = $db->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
/* Fetch all of the remaining rows in the result set */

//print_r($result);  //check to see an actual array
//var_dump($result);

$numrows=count($result);
echo "Total ids found $numrows<br>";

if ( $numrows > 0 )
{
for ($i = 0; $i < count($result); $i+=3)
    {       $Value1 = $result[$i]['course_name'];
            $Value2 = $result[$i + 1]['course_name'];
            $Value3 = $result[$i + 2]['course_name'];
            echo "Value1: $Value1 Value2: $Value2 Value3: $Value3<br>";
    }

}

由于$i+1,您似乎多次迭代索引$i+2。。也许你可以用$i+=3,因为奇怪的是我什么也得不到。根本没有回音。除了$numrows.Array[id]=>1[0]=>1[img]=>images/img.jpg[1]=>images/img.jpg之外,我检查时会显示值的数组。我回显时屏幕上没有输出。古怪看起来像一个var_dump,确定您没有编辑代码吗?var_dump=objectPDOStatement2 1{[queryString]=>string101 SELECT id,FROM table}所以它计算numrow,但可能PDO没有处理查询?echo什么都没有显示?您的php设置是否显示错误?我没有任何错误,只是var_转储看起来不正确。Print_r也没有显示array=PDOStatement对象[queryString]=>SELECT id,img FROM表,我得到的是它确实对行进行了计数。
$sth = $db->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
/* Fetch all of the remaining rows in the result set */

//print_r($result);  //check to see an actual array
//var_dump($result);

$numrows=count($result);
echo "Total ids found $numrows<br>";

if ( $numrows > 0 )
{
for ($i = 0; $i < count($result); $i+=3)
    {       $Value1 = $result[$i]['course_name'];
            $Value2 = $result[$i + 1]['course_name'];
            $Value3 = $result[$i + 2]['course_name'];
            echo "Value1: $Value1 Value2: $Value2 Value3: $Value3<br>";
    }

}