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

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

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

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

PHP中如何解决这个问题?


当前回答

我有点喜欢下面的,因为我觉得它相当整洁。让我们假设我们正在创建一个字符串,所有元素之间都有分隔符:例如a,b,c

$first = true;
foreach ( $items as $item ) {
    $str = ($first)?$first=false:", ".$item;
}

其他回答

您可以执行count()。

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

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

end(arr);

只返回最后一个元素。

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

arr[1];

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

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

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

我个人使用这种结构,可以很容易地使用html < ul >和< li >元素:简单地更改其他属性的相等…

数组不能包含假项,只能包含转换为假布尔值的所有其他项。

$table = array( 'a' , 'b', 'c');
$it = reset($table);
while( $it !== false ) {
    echo 'all loops';echo $it;
    $nextIt = next($table);
    if ($nextIt === false || $nextIt === $it) {
            echo 'last loop or two identical items';
    }
    $it = $nextIt;
}

你可以直接得到最后一个索引:

$numItems = 计数($arr);

echo $ giba [numItems-1美元];

如果您需要对除第一个或最后一个元素之外的每个元素都做一些事情,并且仅当数组中有多个元素时,我更喜欢以下解决方案。

我知道在我之前的几个月或一年,上面有很多解决方案,但我觉得这个解决方案本身就相当优雅。每个循环的检查也是一个布尔检查,而不是一个数字“i=(count-1)”检查,这可能会允许更少的开销。

循环的结构可能让人感觉很尴尬,但你可以将它与HTML表标签中的thead(开始)、tfoot(结束)、tbody(当前)的顺序进行比较。

$first = true;
foreach($array as $key => $value) {
    if ($first) {
        $first = false;
        // Do what you want to do before the first element
        echo "List of key, value pairs:\n";
    } else {
        // Do what you want to do at the end of every element
        // except the last, assuming the list has more than one element
        echo "\n";
    }
    // Do what you want to do for the current element
    echo $key . ' => ' . $value;
}

例如,在web开发术语中,如果你想在无序列表(ul)中除了最后一个元素之外的每个元素中添加border-bottom,那么你可以在除了第一个元素之外的每个元素中添加border-top (CSS:first-child,由IE7+和Firefox/Webkit支持这种逻辑,而:last-child不被IE7支持)。

您可以自由地为每个嵌套循环重用$first变量,并且事情会工作得很好,因为在第一次迭代的第一个过程中,每个循环都会使$first为false(因此中断/异常不会引起问题)。

$first = true;
foreach($array as $key => $subArray) {
    if ($first) {
        $string = "List of key => value array pairs:\n";
        $first = false;
    } else {
        echo "\n";
    }

    $string .= $key . '=>(';
    $first = true;
    foreach($subArray as $key => $value) {
        if ($first) {
            $first = false;
        } else {
            $string .= ', ';
        }
        $string .= $key . '=>' . $value;
    }
    $string .= ')';
}
echo $string;

示例输出:

List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)