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

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

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

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

PHP中如何解决这个问题?


当前回答

因为你寻找EOF数组的意图只是为了粘合。请了解下面的策略。你不需要EOF:

$given_array = array('column1'=>'value1',
                     'column2'=>'value2',
                     'column3'=>'value3');

$glue = '';
foreach($given_array as $column_name=>$value){
    $where .= " $glue $column_name = $value"; //appending the glue
    $glue   = 'AND';
}
echo $where;

o/p:

column1 = value1 AND column2 = value2 AND column3 = value3

其他回答

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

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!';
}

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

您可以执行count()。

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

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

end(arr);

只返回最后一个元素。

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

arr[1];

我有一种强烈的感觉,在这个“XY问题”的根源上,OP想要的只是implode()函数。

听起来你想要的是这样的:

$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
}    

也就是说,你不必在php中使用foreach遍历一个“数组”。

你也可以尝试这样让你的查询…这里显示的是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;
?>