我正在使用一些参数编写一个SQL查询创建器。在Java中,只需检查当前的数组位置和数组长度,就可以很容易地从for循环中检测到数组的最后一个元素。
for(int i=0; i< arr.length;i++){
boolean isLastElem = i== (arr.length -1) ? true : false;
}
在PHP中,它们使用非整数索引来访问数组。因此,必须使用foreach循环遍历数组。当您需要做出一些决定时(在我的例子中是在构建查询时追加或/和参数),这就成了问题。
我相信肯定有一些标准的方法来做这件事。
如何在PHP中解决这个问题?
发布于 2009-03-20 06:05:36
听起来你想要这样的东西:
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
if(++$i === $numItems) {
echo "last index!";
}
}
也就是说,你不需要在php中使用foreach
遍历一个“数组”。
发布于 2009-03-20 06:07:09
您可以使用end(array_keys($array))
获取数组的最后一个键的值,并将其与当前键进行比较:
$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
if ($key == $last_key) {
// last element
} else {
// not last element
}
}
发布于 2009-03-20 09:02:01
当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";
并回答你最初的问题“在我的例子中是在构建查询时追加或/和参数”;这将遍历所有的值,然后用“和”将它们连接到一个字符串中,而不是在第一个值之前或最后一个值之后:
$params = [];
foreach ($array as $value) {
$params[] = doSomething($value);
}
$parameters = implode(" and ", $params);
https://stackoverflow.com/questions/665135
复制相似问题