我正在使用一些参数编写 SQL 查询创建器.在 Java 中,只需通过数组长度检查当前数组位置,就可以很容易地从 for 循环内部检测数组的最后一个元素.
I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.
for(int i=0; i< arr.length;i++){
boolean isLastElem = i== (arr.length -1) ? true : false;
}
在 PHP 中,它们有非整数索引来访问数组.因此,您必须使用 foreach 循环遍历数组.当您需要做出一些决定(在我的情况下,在构建查询时附加或/和参数)时,这会成为问题.
In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query).
我相信一定有一些标准的方法可以做到这一点.
I am sure there must be some standard way of doing this.
你如何在 PHP 中解决这个问题?
How do you solve this in PHP?
听起来你想要这样的东西:
It sounds like you want something like this:
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
if(++$i === $numItems) {
echo "last index!";
}
}
话虽如此,您不必在 php 中使用 foreach 迭代数组".
That being said, you don't -have- to iterate over an "array" using foreach in php.
这篇关于在 PHP 中使用 foreach 循环时查找数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
MySQLi准备好的语句&foreach 循环MySQLi prepared statement amp; foreach loop(MySQLi准备好的语句amp;foreach 循环)
mysqli_insert_id() 是从整个服务器还是从同一用户获Is mysqli_insert_id() gets record from whole server or from same user?(mysqli_insert_id() 是从整个服务器还是从同一用户获取记录?)
PHP MySQLi 无法识别登录信息PHP MySQLi doesn#39;t recognize login info(PHP MySQLi 无法识别登录信息)
mysqli_select_db() 需要 2 个参数mysqli_select_db() expects exactly 2 parameters(mysqli_select_db() 需要 2 个参数)
Php mysql pdo 查询:用查询结果填充变量Php mysql pdo query: fill up variable with query result(Php mysql pdo 查询:用查询结果填充变量)
MySQLI 28000/1045 用户“root"@“localhost"的访问MySQLI 28000/1045 Access denied for user #39;root#39;@#39;localhost#39;(MySQLI 28000/1045 用户“root@“localhost的访问被拒绝)