PHP foreach没有迭代第一个结果


PHP foreach not iterating first result

我很困惑为什么第一个结果0没有被迭代。有人能解释一下原因并告诉我需要做些什么才能显示[0]的结果吗?

Here is my Array:
array(3) { [0]=> string(3) "390" [1]=> string(3) "377" [2]=> string(3) "382" } 

请注意[0]结果是如何不通过foreach显示的。最后两个是[1]和[2],结果很好。

您可以在此处查看结果:http://www.rotaryswing.com/swingviewer/videos.php

<?php 
//iterate through video IDS in our DB
foreach ($pieces as $key => $v) {
$sql ="SELECT id, video_name, link, phase FROM videos WHERE id=?";
    if ($stmt = $mysqli->prepare($sql)) {
        $stmt->bind_param("i", $v);
        if ($stmt->execute()) {
            $stmt->bind_result($id, $vid_name, $vid_link, $phase);
            while ($stmt->fetch()) {
                echo "<a style='"font-size: 14px;'" href='http://www.rotaryswing.com/golf- instruction/video/rst-index.php?cat=$phase&subcat=Rotary%20Swing%20Tour&video=$id&id=$vid_link&name=$vid_name' target='"blank'">$vid_name</a><br>";
            }
        }
        else {
            trigger_error("SQL query failed: " . $stmt->error, E_USER_ERROR);
        }
    }
}
?>

当我只回声片段时,它的回声很好。

<?php echo $pieces[0] . "<br/>";?>
<?php echo $pieces[1] . "<br/>";?>
<?php echo $pieces[2] . "<br/>";?>

您可以在数组中使用WHERE IN

# create the correct amount of ?
$placeholder = implode(', ', array_fill(0, count($pieces), '?'));
$sql ="SELECT id, video_name, link, phase FROM videos WHERE id IN ({$placeholder})";
if ($stmt = $mysqli->prepare($sql))
{
    # add at the begin the type of your array the field types
    array_unshift($pieces, implode('', array_fill(0, count($pieces), 'i')));
    # bind the field type and each value
    call_user_func_array(array($stmt, 'bind_param'), $pieces);
    if ($stmt->execute())
    {
        $stmt->bind_result($id, $vid_name, $vid_link, $phase);
        while ($stmt->fetch())
        {
?>
<a style="font-size: 14px;" href="http://www.rotaryswing.com/golf-instruction/video/rst-index.php?cat=<?php echo $phase; ?>&subcat=Rotary%20Swing%20Tour&video=<?php echo $id; ?>&id=<?php echo $vid_link; ?>&name=<?php echo $vid_name; ?>" target="blank"><?php echo $vid_name; ?></a><br>
<?php
        }
    }
    else
    {
        trigger_error("SQL query failed: " . $stmt->error, E_USER_ERROR);
    }
}

使用call_user_func_array(array($stmt, 'bind_param'), $pieces);,我们将每个字段类型和参数绑定到bind_param

使用$placeholder = implode(', ', array_fill(0, count($pieces), '?'));,我们创建具有$pieces所具有的正确占位符数量的字符串,因此如果$pieces具有4个id,它将创建一个类似于?, ?, ?, ?的字符串,然后我们将其附加在IN ({$placeholder}) 的查询中

使用array_unshift($pieces, implode('', array_fill(0, count($pieces), 'i')));,我们创建并附加所有类型作为数组的第一个元素。

正如评论者Dagon所说,将查询置于循环之外。

使用这样的查询:

SELECT id, video_name, link, phase FROM videos WHERE id IN (?)

然后,您可以发送一个查询并一次获取所有数据。

IN ()的内容使用$v = implode(',',$pieces);

使用内爆不应导致数组元素丢失。