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

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

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

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

PHP中如何解决这个问题?


当前回答

另一种方法是记住之前的循环结果,并将其作为最终结果:

    $result = $where = "";
    foreach ($conditions as $col => $val) {
        $result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
        $where .=  " AND ";
    }
    return $this->delete($result);

其他回答

注意:这不起作用,因为调用next()会使数组指针向前移动,因此您将跳过循环中的所有其他元素


为什么这么复杂?

foreach($input as $key => $value) {
    $ret .= "$value";
    if (next($input)==true) $ret .= ",";
}

这将在除最后一个值之外的每个值后面添加a !

当toEnd达到0时,意味着它处于循环的最后一次迭代中。

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

最后一个值在循环之后仍然可用,所以如果你只是想在循环之后用它来做更多的事情,这样更好:

foreach($arr as $key=>$value) {
  //something
}
echo "last index! $key => $value";

如果您不想将最后一个值作为特殊的内部循环。如果您有大型数组,这应该更快。(如果你在相同范围内的循环之后重用数组,你必须先“复制”数组)。

//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop

//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);

//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";

foreach ($array as $key => $value) {
    //do something with all values before the last value
    echo "All except last value: $value", "\n";
}

//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";

并回答您最初的问题“在我的情况下,在构建查询时附加或/和参数”;这将遍历所有值,然后将它们连接到一个字符串中,其中包含“and”,但不是在第一个值之前或最后一个值之后:

$params = [];
foreach ($array as $value) {
    $params[] = doSomething($value);
}
$parameters = implode(" and ", $params);

一种方法是检测迭代器是否有next。如果迭代器没有附加next,则意味着你在最后一个循环中。

foreach ($some_array as $element) {
    if(!next($some_array)) {
         // This is the last $element
    }
}

因为你寻找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

对于SQL查询生成脚本,或任何对第一个或最后一个元素执行不同操作的脚本,避免使用不必要的变量检查要快得多(几乎快两倍)。

目前公认的解决方案使用循环和循环内的检查,将使every_single_iteration,正确的(快速)方法如下:

$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
    $some_item=$arr[$i];
    $i++;
}
$last_item=$arr[$i];
$i++;

一个自制的基准测试显示如下:

Test1: 100000次模型morg

时间:1869.3430423737毫秒

Test2:模型运行100000次

时间:3235.6359958649毫秒