我正在使用一些参数编写SQL查询创建者。在Java中,只需通过数组长度检查当前数组位置,就可以很容易地从for循环中检测数组的最后一个元素。

for(int i=0; i< arr.length;i++){
     boolean isLastElem = i== (arr.length -1) ? true : false;        
}

在PHP中,它们有访问数组的非整数索引。因此必须使用foreach循环遍历数组。当您需要做出某些决定时(在我的例子中,在构建查询时附加或/和参数),这就会出现问题。

我相信一定有某种标准的方法来做这件事。

PHP中如何解决这个问题?


当前回答

你也可以尝试这样让你的查询…这里显示的是INSERT

<?php
 $week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
 $keys = array_keys($week);
 $string = "INSERT INTO my_table ('";
 $string .= implode("','", $keys);
 $string .= "') VALUES ('";
 $string .= implode("','", $week);
 $string .= "');";
 echo $string;
?>

其他回答

<?php foreach($have_comments as $key => $page_comment): ?>
    <?php echo $page_comment;?>
    <?php if($key+1<count($have_comments)): ?> 
        <?php echo ', '; ?>
    <?php endif;?>
<?php endforeach;?>

用"end"怎么样? http://php.net/manual/en/function.end.php

您可以执行count()。

for ($i=0;$i<count(arr);$i++){
    $i == count(arr)-1 ? true : false;
}

或者如果你只寻找最后一个元素,你可以使用end()。

end(arr);

只返回最后一个元素。

而且,你可以用整数来索引php数组。它完全满意

arr[1];

所以,如果你的数组有唯一的数组值,那么确定最后一次迭代是微不足道的:

foreach($array as $element) {
    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

如您所见,如果最后一个元素在数组中只出现一次,则此方法有效,否则将得到假警报。如果不是,则必须比较键(肯定是唯一的)。

foreach($array as $key => $element) {
    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

还要注意严格共配运算符,这在本例中非常重要。

$array  = array("dog", "rabbit", "horse", "rat", "cat");
foreach($array as $index => $animal) {
    if ($index === array_key_first($array))
        echo $animal; // output: dog

    if ($index === array_key_last($array))
        echo $animal; // output: cat
}